教程:从 Angular 单页应用调用 API
本教程是演示如何生成 Angular 单页应用 (SPA) 的系列教程的第 4 部分,将使用 Microsoft 标识平台进行身份验证。 在本教程中,你将从 Angular SPA 调用 Microsoft 图形 API。
本教程的内容:
- 创建对 Microsoft Graph 的 API 调用
- 测试应用程序
先决条件
创建对 Microsoft Graph 的 API 调用
要将 Angular 应用程序配置为与 Microsoft 图形 API 交互,请完成以下步骤:
打开
src/app/profile/profile.component.ts
文件并将内容替换为以下代码片段:// Required for Angular import { Component, OnInit } from '@angular/core'; // Required for the HTTP GET request to Graph import { HttpClient } from '@angular/common/http'; type ProfileType = { businessPhones?: string, displayName?: string, givenName?: string, jobTitle?: string, mail?: string, mobilePhone?: string, officeLocation?: string, preferredLanguage?: string, surname?: string, userPrincipalName?: string, id?: string } @Component({ selector: 'app-profile', templateUrl: './profile.component.html' }) export class ProfileComponent implements OnInit { profile!: ProfileType; tokenExpiration!: string; constructor( private http: HttpClient ) { } // When the page loads, perform an HTTP GET request from the Graph /me endpoint ngOnInit() { this.http.get('https://graph.microsoft.com/v1.0/me') .subscribe(profile => { this.profile = profile; }); this.tokenExpiration = localStorage.getItem('tokenExpiration')!; } }
Angular 中的
ProfileComponent
会从 Microsoft Graph 的/me
终结点中提取用户配置文件数据。 它定义了ProfileType
来构建如displayName
和mail
等属性。 在ngOnInit
中,它使用HttpClient
发送 GET 请求,从而将响应分配给profile
。 它还从localStorage
中的tokenExpiration
检索和存储令牌过期时间。打开
src/app/profile/profile.component.html
文件并将内容替换为以下代码片段:<div class="profile"> <p><strong>Business Phones:</strong> {{profile?.businessPhones}}</p> <p><strong>Display Name:</strong> {{profile?.displayName}}</p> <p><strong>Given Name:</strong> {{profile?.givenName}}</p> <p><strong>Job Title:</strong> {{profile?.jobTitle}}</p> <p><strong>Mail:</strong> {{profile?.mail}}</p> <p><strong>Mobile Phone:</strong> {{profile?.mobilePhone}}</p> <p><strong>Office Location:</strong> {{profile?.officeLocation}}</p> <p><strong>Preferred Language:</strong> {{profile?.preferredLanguage}}</p> <p><strong>Surname:</strong> {{profile?.surname}}</p> <p><strong>User Principal Name:</strong> {{profile?.userPrincipalName}}</p> <p><strong>Profile Id:</strong> {{profile?.id}}</p> <br><br> <p><strong>Token Expiration:</strong> {{tokenExpiration}}</p> <br><br> <p>Refreshing this page will continue to use the cached access token until it nears expiration, at which point a new access token will be requested.</p> </div>
此代码定义了一个显示用户配置文件信息的 HTML 模板,使用 Angular 的内插语法绑定
profile
对象中的属性(例如businessPhones
、displayName
、jobTitle
)。 它还显示tokenExpiration
值,并包括一条说明,指出在缓存的访问令牌接近过期之前,刷新页面将会使用该令牌,并将在过期后请求新的令牌。
测试应用程序
要测试应用程序,请完成以下步骤:
通过在终端中执行以下命令来运行 Angular 应用程序:
ng serve --open
选择“登录”按钮,以向 Microsoft Entra 租户进行身份验证。
登录后,选择“查看配置文件”链接以导航到“配置文件”页。 验证是否显示用户配置文件信息,包括用户名、电子邮件、职务和其他详细信息。
选择“退出登录”按钮以退出应用程序。
后续步骤
尝试以下有关如何构建 Web API 的系列教程,了解如何使用 Microsoft 标识平台。