SharePoint List Operations Using SPFx Solution With JSOM

使用JSOM 需要先执行参考https://docs.microsoft.com/zh-cn/sharepoint/dev/spfx/web-parts/basics/add-an-external-library

加载 SharePoint JSOM

加载 SharePoint JSOM 与加载具有依赖项的非 AMD 脚本本质上属于同一方案。这表示同时使用 globalName 和 globalDependency 两个选项。

 重要

注意,以下方法会导致经典 SharePoint 页面发生错误,因为其中已经加载了 SharePoint JSOM。 如果你需要 Web 部件同时使用经典页面和新式页面,如果 SharePoint JSOM 已经可用,应该先进行检查,如果不可用,则通过使用 SPComponentLoader 动态加载。

 

  1. 安装属于 JSOM 键入依赖项的 Microsoft Ajax 的键入:

    sh复制

    npm install @types/microsoft-ajax --save
    
  2. 安装 JSOM 的键入:

    sh复制

    npm install @types/sharepoint --save
    
  3. 向 config.json 添加项:

    JSON复制

    {
        "sp-init": {
            "path": "https://CONTOSO.sharepoint.com/_layouts/15/init.js",
            "globalName": "$_global_init"
        },
        "microsoft-ajax": {
            "path": "https://CONTOSO.sharepoint.com/_layouts/15/MicrosoftAjax.js",
            "globalName": "Sys",
            "globalDependencies": [ "sp-init" ]
        },
        "sp-runtime": {
            "path": "https://CONTOSO.sharepoint.com/_layouts/15/SP.Runtime.js",
            "globalName": "SP",
            "globalDependencies": [ "microsoft-ajax" ]
        },
        "sharepoint": {
            "path": "https://CONTOSO.sharepoint.com/_layouts/15/SP.js",
            "globalName": "SP",
            "globalDependencies": [ "sp-runtime" ]
        }
    }
    
  4. 在 Web 部件中添加 require 语句:

    TypeScript复制

    require('sp-init');
    require('microsoft-ajax');
    require('sp-runtime');
    require('sharepoint');
    

加载本地化资源

你可以使用 config.json 中一个名为 localizedResources 的映射描述如何加载本地化资源。 此映射中的路径与 lib文件夹相对,其中不能包含前导斜杠 (/)。

在此示例中具有文件夹 src/strings/。在此文件夹中是一些名称为 en-us.jsfr-fr.jsde-de.js 的 JavaScript 文件。因为这些文件中的每一个都必须可通过模块加载程序加载,因此它们必须包含一个 CommonJS 包装器。例如,在 en-us.js 中:

TypeScript复制

  define([], function() {
    return {
      "PropertyPaneDescription": "Description",
      "BasicGroupName": "Group Name",
      "DescriptionFieldLabel": "Description Field"
    }
  });

 

  1. 编辑 config.json 文件。 向 localizedResources 添加项。 {locale} 是区域名称的占位符标记:

    JSON复制

    {
        "strings": "strings/{locale}.js"
    }
    
  2. 添加字符串的键入。在此示例中具有文件 MyStrings.d.ts

    TypeScript复制

    declare interface IStrings {
        webpartTitle: string;
        initialPrompt: string;
        exitPrompt: string;
    }
    
    declare module 'mystrings' {
        const strings: IStrings;
        export = strings;
    }
    
  3. 添加项目中字符串的导入项:

    TypeScript复制

    import * as strings from 'mystrings';
    
  4. 在项目中使用字符串:

    TypeScript复制

    alert(strings.initialPrompt);

Here, let us look at performing basic list operations, using SharePoint JavaScript Object Model (JSOM) on SharePoint Framework Solutions (SPFx).

Microsoft provides the packages for supporting JSOM operations. Usually in the traditional approach, JavaScript files required for JSOM operations are MicrosoftAjax.js, SP.js, SP.runtime.js etc. For SPFx solutions, the required files can be included by installing the required typings.

In my previous article, you will have learned building the code, using JSOM approach on SharePoint Framework Solutions.

The support files are installed, using the typings. Install the required typings (Microsoft.ajax and Sharepoint) before creating the project.

Create the project with no JavaScript framework option, using the command yo @microsoft/sharepoint. In Render method, insert the necessary HTML wrapper to display the data.

Declare other methods to process the data. Four methods are declared to retrieve SharePoint data. 

  • Get Lists
  • Get List by Title
  • Create List
  • Delete List 

Get lists

Let us look at retrieving all the lists from SharePoint site, using JSOM approach.

The context of the object is set and then the list collection will be retrieved, using the Web object. The list collection is loaded and executed with the context before looking at the data. Now, using Get Enumerator method, individual list properties are retrieved and displayed.

  1. public GetLists(){  
  2.     var htmlContext = this;  
  3.     let siteContent:string = "";  
  4.     const context: SP.ClientContext = new SP.ClientContext(this.context.pageContext.web.absoluteUrl);  
  5.     const web: SP.Web = context.get_web();  
  6.     const lists: SP.ListCollection = web.get_lists();  
  7.       
  8.     context.load(lists);  
  9.     context.executeQueryAsync(function () {    
  10.       var listenum = lists.getEnumerator();    
  11.       while (listenum.moveNext()) {    
  12.           var listItem = listenum.get_current();    
  13.             
  14.           siteContent += `<div>  
  15.                           <span>${listItem.get_title()}</span>  
  16.                         </div>`;    
  17.       }    
  18.         
  19.       htmlContext.domElement.querySelector("#siteContent").innerHTML =siteContent;      
  20.     },  
  21.     function(sender,args){  
  22.       console.log(args.get_message());  
  23.     });  
  24.   }   

Get list by Title

Let us see retrieving the required list, using the title with JSOM approach.

Like the above method, the context is used to retrieve the list collection, using the Web object with context URL. From the list collection, the required list is extracted with getbytitle() method. Now, the list is loaded and executed, using the context. In the success method, the properties are displayed.

  1. public GetList(){  
  2.     var htmlContext = this;  
  3.     let siteContent:string = "";  
  4.     const context: SP.ClientContext = new SP.ClientContext(this.context.pageContext.web.absoluteUrl);  
  5.     const web: SP.Web = context.get_web();  
  6.     const lists: SP.ListCollection = web.get_lists();  
  7.     const list: SP.List = lists.getByTitle("TestList");  
  8.       
  9.     context.load(list);  
  10.     context.executeQueryAsync(function () {    
  11.       siteContent += `<div>  
  12.                           <div><h2>Title   : ${list.get_title()}</h2></div>  
  13.                           <div>Description : ${list.get_description()}</div>  
  14.                           <div>Template    : ${list.get_baseTemplate()}</div>  
  15.                           <div>Total Items : ${list.get_itemCount()}</div>  
  16.                         </div>`;   
  17.         
  18.       htmlContext.domElement.querySelector("#siteContent").innerHTML =siteContent;      
  19.     },  
  20.     function(sender,args){  
  21.       console.log(args.get_message());  
  22.     });  
  23.   }   

Create list

Let us create a list, using JSOM approach. Like the previous method, the list collection is retrieved. To the list collection, a new list is added using the list creation information object. The list creation object contains the basic list information. Now, the list is loaded and executed , using the context.

  1. public CreateList(){  
  2.     var htmlContext = this;  
  3.     let siteContent:string = "";  
  4.     const context: SP.ClientContext = new SP.ClientContext(this.context.pageContext.web.absoluteUrl);  
  5.     const web: SP.Web = context.get_web();  
  6.     const lists: SP.ListCollection = web.get_lists();  
  7.       
  8.     var listCreationInfo = new SP.ListCreationInformation();  
  9.     listCreationInfo.set_title('TestList1');  
  10.     listCreationInfo.set_templateType(SP.ListTemplateType.genericList);  
  11.   
  12.     const list:SP.List = lists.add(listCreationInfo);  
  13.   
  14.       
  15.     context.load(list);  
  16.     context.executeQueryAsync(function () {    
  17.       siteContent += `<div>  
  18.                           <div><h2>Title   : ${list.get_title()}</h2></div>  
  19.                           <div>Description : ${list.get_description()}</div>  
  20.                           <div>Template    : ${list.get_baseTemplate()}</div>  
  21.                           <div>Total Items : ${list.get_itemCount()}</div>  
  22.                         </div>`;   
  23.         
  24.       htmlContext.domElement.querySelector("#siteContent").innerHTML =siteContent;      
  25.     },  
  26.     function(sender,args){  
  27.       console.log(args.get_message());  
  28.     });  
  29.   }    

Delete list

Here, we will see deleting the existing list from the site by JSOM approach. The list is retrieved like Get list by Title method. Now, the list object is deleted, using deleteObject() method. Now, the context is executed.

  1. public DeleteList(){  
  2.     var htmlContext = this;  
  3.     let siteContent:string = "";  
  4.     const context: SP.ClientContext = new SP.ClientContext(this.context.pageContext.web.absoluteUrl);  
  5.     const web: SP.Web = context.get_web();  
  6.     const lists: SP.ListCollection = web.get_lists();  
  7.     const list:SP.List = lists.getByTitle("TestList1");  
  8.   
  9.     list.deleteObject();  
  10.     context.executeQueryAsync(function () {    
  11.       siteContent += `<div>TestList1 list deleted</div>`;   
  12.         
  13.       htmlContext.domElement.querySelector("#siteContent").innerHTML =siteContent;      
  14.     },  
  15.     function(sender,args){  
  16.       console.log(args.get_message());  
  17.     });  
  18.   }    

 

Deploy/ Run

To test the solution, using the command prompt, run Gulp serve command for testing. From the required site, open the workbench.aspx file and add the Web part. The Web part will display the site properties.

To deploy the solution, the solution should be bundled and packaged. Now, the files should be uploaded to SharePoint site (Office 365 site) and then the app is deployed. 

The article given below shows the detailed steps for bundling, packaging and deploying. 

Summary

Thus, you have learned developing the list operations on SharePoint Framework Solutions with JavaScript Object Model (JSOM) approach.

 

https://www.c-sharpcorner.com/article/sharepoint-list-operations-using-spfx-solution-with-jsom/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值