You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Angular应用连接至SharePoint以获取文件夹资源列表?

在Angular中列出SharePoint文件夹内所有资源的解决方案

核心思路

通过Microsoft Graph API访问SharePoint文件资源,配合MSAL完成身份验证,在Angular中实现文件夹内容的读取与展示。


步骤1:配置Azure AD应用权限

  1. 登录Azure门户,注册Angular应用,获取clientId和tenantId。
  2. 为应用添加Delegated权限:Files.Read.All或Sites.Read.All,并授予管理员同意。

步骤2:安装依赖包

在Angular项目根目录执行命令:

npm install @microsoft/microsoft-graph-client @azure/msal-angular @azure/msal-browser

步骤3:配置MSAL身份验证模块

在app.module.ts中导入并配置MSAL:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { MsalModule, MsalService, MSAL_INSTANCE } from '@azure/msal-angular';
import { PublicClientApplication } from '@azure/msal-browser';
import { AppComponent } from './app.component';

export function MSALInstanceFactory() {
  return new PublicClientApplication({
    auth: {
      clientId: '你的Azure应用clientId',
      authority: 'https://login.microsoftonline.com/你的tenantId',
      redirectUri: 'http://localhost:4200' // 你的Angular应用地址
    }
  });
}

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, MsalModule],
  providers: [
    {
      provide: MSAL_INSTANCE,
      useFactory: MSALInstanceFactory
    },
    MsalService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

步骤4:创建SharePoint数据服务

新建sharepoint.service.ts,封装Graph API调用:

import { Injectable } from '@angular/core';
import { MsalService } from '@azure/msal-angular';
import { Client } from '@microsoft/microsoft-graph-client';
import { AuthProvider } from '@microsoft/microsoft-graph-client/lib/src/IAuthProvider';

@Injectable({ providedIn: 'root' })
export class SharePointService {
  private graphClient: Client;

  constructor(private msalService: MsalService) {
    const authProvider: AuthProvider = async (done) => {
      const account = this.msalService.instance.getActiveAccount();
      if (!account) {
        throw new Error('No active account found');
      }
      const response = await this.msalService.instance.acquireTokenSilent({
        account,
        scopes: ['Files.Read.All']
      });
      done(null, response.accessToken);
    };
    this.graphClient = Client.init({ authProvider });
  }

  // 获取指定文件夹下的所有资源
  async getFolderItems(siteId: string, folderId: string) {
    try {
      const items = await this.graphClient
        .api(`/sites/${siteId}/drive/items/${folderId}/children`)
        .get();
      return items.value;
    } catch (error) {
      console.error('获取文件夹内容失败:', error);
      throw error;
    }
  }
}
  • 替换siteId和folderId:siteId可从SharePoint站点URL提取(格式为{domain},{site-guid},{web-guid});folderId可以是文件夹ID或路径(如/Documents/MyFolder)。

步骤5:在组件中调用服务并展示

组件TS文件:

import { Component, OnInit } from '@angular/core';
import { SharePointService } from './sharepoint.service';

@Component({
  selector: 'app-folder-view',
  templateUrl: './folder-view.component.html'
})
export class FolderViewComponent implements OnInit {
  folderItems: any[] = [];

  constructor(private spService: SharePointService) { }

  async ngOnInit() {
    // 替换为你的siteId和folderId
    const siteId = 'contoso.sharepoint.com,xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx,xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx';
    const folderId = 'xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx';
    try {
      this.folderItems = await this.spService.getFolderItems(siteId, folderId);
    } catch (error) {
      console.error('加载失败:', error);
    }
  }
}

对应的HTML模板:

<h3>SharePoint文件夹内容</h3>
<ul *ngIf="folderItems.length > 0">
  <li *ngFor="let item of folderItems">
    <span>{{ item.name }}</span>
    <span> - {{ item.size }} bytes</span>
  </li>
</ul>
<p *ngIf="folderItems.length === 0">文件夹为空或加载失败</p>

内容的提问来源于stack exchange,提问作者Santiago Sanchez Correa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 21:18:37