如何在angular中添加我在localstorage中的标头标记

问题描述 投票:0回答:2

我在我的auth.service和auth.interceptor.ts代码中有这些方法,以便从头部获取令牌,我想用post方法发送它应该添加到头部以便设置令牌?任何帮助深表感谢!!

 //shop.service.ts

const httpOptions = {

headers: new HttpHeaders({ 'Content-Type': 'application/json', 
'Authorization': 'X-OBSERVATORY-AUTH'}) 

};

addShop (shop: Shop): Observable<Shop> {

return this.http.post<Shop>(this.shopsUrl, shop, httpOptions);
}


// auth.interceptor.ts

  intercept(req: HttpRequest<any>, next: HttpHandler) {

  const authToken = this.authService.getToken();

  const authRequest = req.clone({

    headers: req.headers.set("Authorization", "Bearer " + authToken)

  });

  return next.handle(authRequest);
}



//auth.service.ts

getToken() {
return this.token;
}


login( username: string,  password: string) {

var user: User = {  username: username, password: password };
this.http 
  .post<any>("http://localhost:3000/observatory/api/login",user, 
   {observe:'response'})
  .subscribe((res) => {
    const token = res.headers.get('X-OBSERVATORY-AUTH');
    console.log(token);
    this.token = token;

    if (token!==null) {

      this.isAuthenticated = true;
      this.userId = res.body._id;
      this.isAdmin=res.body.isAdmin;
      this.userAdmin=res.body.isAdmin;
      this.username=res.body.username;
      this.authStatusListener.next(true);
      this.saveAuthData(token, this.userId,this.username, this.isAdmin);

} });

angular typescript
2个回答
0
投票

你快到了。 shop.service.ts应该添加标题就好了。在auth.service.ts做同样的事情:

this.http.post<any>(url, user, { 
    headers: new HttpHeaders({ 
      'Content-Type': 'application/json', 
      'Authorization': 'X-OBSERVATORY-AUTH'
    }), 
    observe: 'response'
  });

文件:https://angular.io/guide/http#adding-headers

要在所有(或几乎所有)HTTP请求上添加标头,请使用HTTP拦截器(请参阅@Chenna的评论)

Edit:

发布未经测试的代码的道歉。请参阅Angular 4/5 HttpClient: Argument of type string is not assignable to 'body',了解先前版本产生错误的原因。简而言之,你需要内联observe或使用一些丑陋的技巧。

或者:使用HTTP拦截器。结束所有的烦恼。


0
投票

您已经创建了拦截器。您只需要在模块中提供它,以便它可以拦截请求。

providers: [{ provide: HTTP_INTERCEPTORS, useClass: YourInterceptorClass, multi: true }]
© www.soinside.com 2019 - 2024. All rights reserved.