次の方法で共有


チュートリアル: Angular シングルページ アプリから API を呼び出す

このチュートリアルは、認証に Microsoft ID プラットフォームを使用する Angular シングルページ アプリ (SPA) の構築を示すシリーズのパート 4 です。 このチュートリアルでは、Angular SPA から Microsoft Graph API を呼び出します。

このチュートリアルの内容:

  • Microsoft Graph への API 呼び出しを作成する
  • アプリケーションをテストする

前提条件

Microsoft Graph への API 呼び出しを作成する

Microsoft Graph API と対話するように Angular アプリケーションを構成するには、次の手順を実行します。

  1. 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 エンドポイントからユーザー プロファイル データをフェッチします。 ProfileTypedisplayName などのプロパティを構造化するように mail を定義します。 ngOnInit では、HttpClient を使用して GET 要求を送信し、応答を profile に割り当てます。 また、localStorage からトークンの有効期限を取得して tokenExpiration に格納します。

  2. 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>
    

    このコードでは、Angular の補間構文を使用して profile オブジェクト (たとえば、businessPhonesdisplayNamejobTitle) からプロパティをバインドして、ユーザー プロファイル情報を表示する HTML テンプレートを定義します。 また、tokenExpiration 値も表示され、ページを更新すると、有効期限が近づくまでキャッシュされたアクセス トークンが使用され、その後新しいトークンが要求されることを示すメモが含まれています。

アプリケーションをテストする

アプリケーションをテストするには、次の手順を実行します。

  1. ターミナルで次のコマンドを実行して、Angular アプリケーションを実行します。

    ng serve --open
    
  2. [サインイン] ボタンを選択して、Microsoft Entra テナントで認証します。

  3. サインインした後、[プロファイルの表示] リンクを選択して、[プロファイル] ページに移動します。 ユーザーの名前、電子メール、役職、その他の詳細など、ユーザー プロファイル情報が表示されていることを確認します。

    API 呼び出しの結果を示す JavaScript アプリのスクリーンショット。

  4. [サインアウト] ボタンを選択して、アプリケーションからサインアウトします。

次のステップ

Web API を構築する方法に関する次のチュートリアル シリーズを試して、Microsoft ID プラットフォームを使用する方法について説明します。