HttpClient没有在服务上下文中发送令牌



我使用Msal包构建了一个Angular 11应用程序。

Msal提供的拦截器会自动添加所需的授权头和令牌。但是,只有当我使用提供给组件的HttpClient时,它才能工作。如果我使用注入到服务中的HttpClient,则不会设置授权头。

如果Http拦截器只对组件执行,一切都会像这样。

我的应用程序的结构是香草:

  • 应用程序
    • 组件myComponent
      • 添加
    • 共享
      • 服务
        • myService组件也有专门的模块和服务。我试图在app.module和/或service的providers部分声明我的服务。模块,但运气不好。所有模块都导入到app.module

任何想法?

编辑我的app模块导入:

imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
LayoutModule,

// Msal Module
MsalModule,
HttpClientModule,
...
]

HttpClientModule没有被导入到其他地方

调用者类:

export class GameListComponent {
games: Game[];
constructor(private gameService: GameService,
private http: HttpClient) { }
service() { // Token not sent
this.gameService.list().subscribe(response=>{
this.games = response;
console.log(this.games);
});
}
list() { // Token is correctly sent
this.http.get("https://localhost:5001/api/Game/All")
.subscribe(list=>console.log(list));
}
}
}

服务:

@Injectable({
providedIn: 'root'
})
export class GameService {
constructor(private http: HttpClient) { }
list():Observable<Game[]> {
return this.http.get<Game[]>("api/Game/All");
}
}

编辑2:我忘了说在我的app上有一个proxy.conf。

在服务的情况下,使用proxy.conf并且调用在正确的端口上完成,但是没有授权头.

如果我用完整的地址+端口调用API,则不使用代理并添加授权头(并且调用成功)。

仍在寻找哪里出错了…

把服务放在共享模块中是错误的,因为每个惰性加载的模块都会创建注入器,而在你的例子中,有些服务是重复的。更常见的方法是把服务放到/core模块中,这个模块只导入一次——导入到主应用模块。

最新更新