Angular 我无法在应用程序初始化后使用baseRequestOptions设置默认标头为什么?
我想在身份验证之后设置用户令牌,以便在其他下一个请求中使用它。我这样做:Angular 我无法在应用程序初始化后使用baseRequestOptions设置默认标头为什么?,angular,angular-http,Angular,Angular Http,我想在身份验证之后设置用户令牌,以便在其他下一个请求中使用它。我这样做: @Injectable() export class CustomRequestOptionsService extends BaseRequestOptions { constructor(private local: LocalStorageService) { super(); } setToken(token: string) { this.setAuthorization('token');
@Injectable()
export class CustomRequestOptionsService extends BaseRequestOptions {
constructor(private local: LocalStorageService) {
super();
}
setToken(token: string) {
this.setAuthorization('token');
this.local.set("token",token);
}
private setAuthorization(token: string) {
this.headers.set( 'Authorization',`Bearer ${token}`);
}
}
我的组件
register() {
this.userService.register(this.user).subscribe((response: any) => {
if (response.token) {
this.options.setToken(response.token); // i set the token here
return this.router.navigate(['/home']);
}
});
}
在此之后,我使用Authorization头发出另一个请求。但是标头不包含授权标头和令牌。为什么???您需要设置提供程序,为RequestOptions提供自定义类
providers: [
{ provide: RequestOptions, useClass: CustomRequestOptionsService }
]
请看以下文章: