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

如何在AngularJS类中导入并使用msalService获取令牌?

解决ES6类中调用msalAuthenticationService的问题

问题根源

@azure/msal-angularjs是为AngularJS的依赖注入(DI)体系设计的,直接通过import导入无法获取到可使用的服务实例——你导入的只是模块本身,而非AngularJS容器初始化后的服务实例。

方案一:将ES6类转为AngularJS服务(推荐)

贴合AngularJS生态,无需深度重构,直接把类改成AngularJS服务,通过DI注入msalAuthenticationService:

import axios from 'axios';

angular.module('app')
.service('SuperDuperApiClient', ['msalAuthenticationService', function(msalService) {
  this.baseUrl = 'xxxxxx/api';
  this.uiUrl = 'xxxxx';

  const apiAccessToken = sessionStorage.getItem("api-access-token");
  console.log("API TOKEN : ", apiAccessToken);
  
  if (!apiAccessToken) {
    msalService.acquireTokenSilent(['xxxxx/Api/user_impersonation'])
      .then(token => sessionStorage.setItem('api-access-token', token))
      .catch(error => {
        // 静默获取失败时触发登录跳转
        msalService.loginRedirect(['xxxxx/Api/user_impersonation']);
      });
  }

  // 示例API方法
  this.fetchData = function(endpoint) {
    const token = sessionStorage.getItem("api-access-token");
    return axios.get(`${this.baseUrl}/${endpoint}`, {
      headers: { Authorization: `Bearer ${token}` }
    });
  };
}]);

之后你可以在AngularJS的控制器、其他服务中通过DI注入SuperDuperApiClient使用。

方案二:保留ES6类,从AngularJS注入器获取服务实例

如果必须保留ES6类结构,可通过AngularJS的全局注入器获取msalAuthenticationService实例:

import axios from 'axios';
import angular from 'angular';

export class SuperDuperApiClient {
  baseUrl = 'xxxxxx/api';
  uiUrl = 'xxxxx';

  constructor() {
    // 从AngularJS应用模块的注入器中获取服务实例
    const msalService = angular.injector(['app']).get('msalAuthenticationService');
    
    const apiAccessToken = sessionStorage.getItem("api-access-token");
    console.log("API TOKEN : ", apiAccessToken);
    
    if (!apiAccessToken) {
      msalService.acquireTokenSilent(['xxxxx/Api/user_impersonation'])
        .then(token => sessionStorage.setItem('api-access-token', token))
        .catch(error => msalService.loginRedirect(['xxxxx/Api/user_impersonation']));
    }
  }

  async fetchData(endpoint) {
    const token = sessionStorage.getItem("api-access-token");
    return axios.get(`${this.baseUrl}/${endpoint}`, {
      headers: { Authorization: `Bearer ${token}` }
    });
  }
}

注意:这种方式要确保AngularJS的app模块已经完成初始化,否则injector会找不到服务。

内容的提问来源于stack exchange,提问作者Terje Nygård

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 08:12:53