【问题标题】:How to call a REST API endpoint inside TypeScript and get its results如何在 TypeScript 中调用 REST API 端点并获取其结果
【发布时间】:2022-01-01 00:20:13
【问题描述】:

在我的 React SPFx Web 部件中,我需要获取当前的 SharePoint 页面标题,为此我需要运行此 API 调用:-

let listTitle: string = this.props.context.pageContext.list.title;
let pageItemId: number = this.props.context.pageContext.listItem.id;

let url = `${this.props.context.pageContext.web.absoluteUrl}/_api/lists/getbytitle('${listTitle}')/items(${pageItemId})?$select=ID,Title`;

那么我如何调用上面的 URL 并获取它应该返回的字符串呢?

谢谢

我尝试了以下,但该函数将返回 null

private GetPageTitle()
  { let listTitle: string = this.props.context.pageContext.list.title;
    let pageItemId: number = this.props.context.pageContext.listItem.id;
    
    let url = `${this.props.context.pageContext.web.absoluteUrl}/_api/lists/getbytitle('${listTitle}')/items(${pageItemId})?$Title`;
    return (RelatedTopics.getSPData(this.client, url));

  }

【问题讨论】:

    标签: reactjs typescript spfx


    【解决方案1】:

    您可以使用 pnp js 包进行 Sharepoint Api 调用或构建 spHttpClient。

    PNP JShttps://pnp.github.io/pnpjs/sp/items/

    import { sp } from '@pnp/sp';
    let url = await sp.web.lists.getByTitle(listTitle).items.getById(pageItemId).select('ID','Title').get();
    

    spHttpClient

    import { ISPHttpClientOptions, SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';
    let url: string = '[endpoint url]';
    this.props.context.spHttpClient.get(url, SPHttpClient.configurations.v1, httpClientOptions).then((response: SPHttpClientResponse) => {
    if (response.ok) {
     return response.json();
    } else {
     reject(error);
    }});
    

    【讨论】:

    • 我的回答有用吗?
    猜你喜欢
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 2021-12-23
    • 2016-10-13
    • 1970-01-01
    • 2021-06-27
    • 2017-12-11
    • 2019-11-04
    相关资源
    最近更新 更多