我想在身份验证后设置用户令牌,以便在其他下一个请求中使用它。我这样做:
@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']);
}
});
}
在此之后,我使用授权标题发出另一个请求。但标题不包含授权标头和令牌。为什么???
答案 0 :(得分:0)
您需要设置提供程序,以便为RequestOptions提供自定义类。
providers: [
{ provide: RequestOptions, useClass: CustomRequestOptionsService }
]
查看以下文章: https://blog.alex-miller.co/angular/2017/05/13/default-headers-in-angular.html