简体   繁体   English

Angular 8:无法设置标题

[英]Angular 8: unable to set headers

I want to call a service from my component:我想从我的组件调用服务:

getToken() {
  const httpOptions = {headers: new HttpHeaders({ 'Authorization': 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==' })};
  return this.http.post(this.rootUrl + "oauth/token?client_id=spring-security-oauth2-read-write-client&password=root1234&username=tarak@bambootv.com&grant_type=password", httpOptions);
}

The call not showing the Authorization , check the image below:呼叫未显示Authorization ,请查看下图:

在此处输入图片说明

You're sending the header as the request body.您将标头作为请求正文发送。

You need to pass it as a third param to the call:您需要将其作为第三个参数传递给调用:

this.http.post(url, null, httpOptions)

try this尝试这个

getToken() {
    const httpOptions = {
        headers: new HttpHeaders({
            'Authorization': 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==',
        })
    };
    const Url = this.rootUrl + "oauth/token?client_id=spring-security-oauth2-read-write-client&password=root1234&username=tarak@bambootv.com&grant_type=password";
    return this.http.post(Url,null, httpOptions)
}

You can use HttpInterceptor您可以使用HttpInterceptor

It will send token with every request.它将随每个请求发送令牌。

@Injectable()
export class ApiTokenInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    request = request.clone({
      setHeaders: {
        Authorization: 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA=='
      }
     });       
    return next.handle(request);
   }
}

send header as third params.发送标头作为第三个参数。 Like喜欢

const httpOptions = {headers: new HttpHeaders({ 'Authorization': 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==' })};
  return this.http.post(this.rootUrl + "oauth/token?client_id=spring-security-oauth2-read-write-client&password=root1234&username=tarak@bambootv.com&grant_type=password", {},httpOptions);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM