首页 > 解决方案 > SPFx 使用 @pnp/sp 创建列表

问题描述

我正在尝试使用@pnp/sp创建自定义列表,在我的例程中我需要检查列表是否存在,如果不存在,我将创建列表并添加其列。

下面的代码有时会起作用,猜想是因为sp.web.*方法是异步的,它会导致问题。

那么,1)检查特定列表,2)如果列表不存在则添加列表,3)将字段添加到列表中的正确方法是什么?

sp.web.lists.ensure("SliceBox").then( List => {    
    List.fields.getByTitle("Body").get().catch( f => {
        f.fields.addMultilineText("Body", 4, true, false, false, true);
    });

    List.fields.getByTitle("Link").get().catch( f => {
        f.fields.addUrl("Link", UrlFieldFormatType.Hyperlink);
    });

    List.fields.getByTitle("Visible").get().catch( f => {
        f.fields.addBoolean("Visible");
    });
})
.catch( err => {
    console.log("> Failure: ", err);
});

如果我尝试非常明确的方式(见下文)也没关系,它也会失败:

sp.web.lists.ensure("SliceBox").then( List => {
    sp.web.lists.getByTitle("SliceBox").fields.getByTitle("Body").get().catch( f => {
        f.fields.addMultilineText("Body", 4, true, false, false, true);
    });        
    // ... shortened for brevity ...
})
.catch( err => {
    console.log("> Failure: ", err);
});

标签: typescriptsharepoint-onlinespfx

解决方案


我的示例测试代码运行良好。

sp.web.lists.ensure("SliceBox").then( sliceBox => {                        
      sliceBox.list.fields.getByTitle("Visible").get().catch( f => {
        sliceBox.list.fields.addBoolean("Visible");
        alert('fieldAdded');
      });

  })

更新:

尝试这个:

sp.web.lists.ensure("SliceBox").then( sliceBox => {                        
      sliceBox.list.fields.getByTitle("Visible").get().catch( f => {
        sliceBox.list.fields.addBoolean("Visible").then(f =>{
          sliceBox.list.fields.getByTitle("Link").get().catch( f => {
            sliceBox.list.fields.addUrl("Link", UrlFieldFormatType.Hyperlink);
            alert('done');
        });
        })

      });

  })

推荐阅读