SharePoint Online SPFx Web部件綁定數據

  前言html

  在上一篇文章裏,咱們爲你們介紹瞭如何建立SPFx Web部件,可是沒有說如何獲取SharePoint 網站數據。這篇文章,咱們就爲你們演示,如何利用列表數據模型和SharePoint SPFx模塊,讀取SharePoint 網站數據並展現出來。web

  正文json

  1.提早建立好數據列表,以下圖:api

 

  2.用Visual Studio Code打開Web部件文件,以下圖:dom

 

  3.在頭部定義列表模型,以下圖:測試

export interface ISPLists {
  value: ISPList[];
}
export
interface ISPList { Title: string; Id: string; }

  4.添加執行REST API請求的幫助程序類 spHttpClient網站

import {
  SPHttpClient,
  SPHttpClientResponse
} from '@microsoft/sp-http';

  5.添加列表模型和幫助程序類位置,以下圖:this

 

  6.添加請求數據的方法,調用REST服務獲取數據,方法以下:spa

private _getListData(): Promise<ISPLists> {
  return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + `/_api/web/lists/getbytitle('MyList')/items`, SPHttpClient.configurations.v1)
    .then((response: SPHttpClientResponse) => {
      return response.json();
    });
}

  7.添加渲染數據的方法,渲染成咱們須要展現的格式,方法以下:3d

private _renderList(items: ISPList[]): void {
  let html: string = '';

  items.forEach((item: ISPList) => {
    html += `<div>${item.Title}</div>`;
  });

  const listContainer: Element = this.domElement.querySelector('#MyContainer');
  listContainer.innerHTML = html;
}

  8.修改渲染Web部件的方法,將獲取的數據渲染到Web部件,方法以下:

public render(): void {
  this.domElement.innerHTML = `<div id="MyContainer" />`;

  this._getListData()
    .then((response) => {
      this._renderList(response.value);
    });
}

  9.添加方法的位置,以下圖:

 

  10.在SharePoint Online站點中測試SPFx Web部件,以下圖:

 

  結束語

  至此,咱們看到SPFx Web部件,已經獲取到了SharePoint Online站點中的列表數據。以後,咱們就能夠把部件部署到網站中,使用了。

相關文章
相關標籤/搜索