首页 > 解决方案 > 从 SharePoint 调用图形 API

问题描述

我需要从 spfx webpart 调用 Graph API。

之前我们使用了以下方法:

import { MSGraphClient } from '@microsoft/sp-client-preview';

但后来我们才知道,MSGraphClient 现在在 sp-client-preview 中已经被贬值了。

我还检查了 Microsoft 文档中提到的以下方法。

import { MSGraphClient } from '@microsoft/sp-http';

但它给出了如下错误:

模块 '"d:/O365/upload-onedrive/node_modules/@microsoft/sp-http/dist/index-internal"' 没有导出成员 'MSGraphClient'

我们现在使用的 SPFx 版本是 1.6

现在有什么方法可以从 spfx 调用 Graph API 吗?

标签: microsoft-graph-apisharepoint-onlinespfx

解决方案


当然我们可以在 SPFx 中使用 Graph。

图+adal+SPFx步骤:

  1. 在Azure 门户中创建应用程序。单击清单,然后将“ oauth2AllowImplicitFlow ”值更改为 true
  2. 转到Settings->Required Permissions->ADD->Select an API->Microsoft Graph,选择权限,然后Grant Permissions

  3. 构建 HelloWorld SPFx 项目:https ://docs.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/get-started/build-a-hello-world-web-part

  4. 添加和 IAdalConfig.ts 和 WebPartAuthenticationContext.js 补丁文件

    提示:如果 node_modules/@types 文件夹中没有 adal 模块,最好使用命令手动安装模块:npm install @types/adal@1.0.29

  5. 将以下代码添加到render()

      // Make an AJAX request to the Graph API and print the response as JSON.
      var getToken;
    
      var getCurrentUser = function (access_token) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'https://graph.microsoft.com/v1.0/me', true);
        xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);
    
        xhr.onreadystatechange = function () {
    
          if (xhr.readyState === 4 && xhr.status === 200) {
    
            // Do something with the response
    
            getToken=JSON.stringify(JSON.parse(xhr.responseText), null, '  ');
            console.log('get Graph APi information=='+getToken);
          } else {
            // TODO: Do something with the error (or non-200 responses)
          //  console.log(' error');
          }
        };
        xhr.send();
    

推荐阅读