http.get
在const headers
如何设置授权?我想使用pageLoadTimeout()
中保存的承载令牌。这就是全部。感谢
编辑:我忘了提到我想知道如何在这里手动设置它而不是拦截器,所有教程都有拦截器,所以我无法弄清楚
答案 0 :(得分:2)
试试这个:
import {Component, OnInit} from '@angular/core';
import {HttpClient, HttpErrorResponse, HttpResponse} from '@angular/common/http';
@Component({
selector: 'git',
templateUrl: './git.component.html'
})
export class GitComponent implements OnInit {
constructor(private http: HttpClient) {
}
ngOnInit(): void {
const headers = 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJzYXNobyIsImF1dGgiOiJST0xFX1VTRVIiLCJleHAiOjE1MjQwODcyMzJ9.MUv5RgI9LxQyrrCfjfX8HR2-XiQmz4vjLqH7V_0Du7VFLC0WrK_y3FfeNoT2Nj_uguIK2ss7jv-LNiHuCGtz4A';
this.http.get('http://localhost:8080/links/all', {
headers: new HttpHeaders().set('Authorization', headers )
})
.subscribe((e) => {
console.log(e);
}, (err: HttpErrorResponse) => {
console.log(err);
});
}
}
答案 1 :(得分:1)
尝试这样的事情:
let authorization: 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJzYXNobyIsImF1dGgiOiJST0xFX1VTRVIiLCJleHAiOjE1MjQwODcyMzJ9.MUv5RgI9LxQyrrCfjfX8HR2-XiQmz4vjLqH7V_0Du7VFLC0WrK_y3FfeNoT2Nj_uguIK2ss7jv-LNiHuCGtz4A'
let header: Headers = new Headers;
header.set('authorization', this.authorization);
this.http.get('http://localhost:8080/links/all',
{headers: header}).subscribe((e) => {
console.log(e);
}, (err: HttpErrorResponse) => {
console.log(err);
});
答案 2 :(得分:0)
您可以查看Angular http拦截器,将令牌附加到每个传出请求: https://medium.com/@ryanchenkie_40935/angular-authentication-using-the-http-client-and-http-interceptors-2f9d1540eb8
答案 3 :(得分:0)
你需要你的标题对象 另一个对象get(....., { headers }
)
第二个arg是一般options
个对象,headers
,请求params
等。请参阅https://angular.io/api/common/http/HttpClient
(与其他一些答案相反,您不需要在HttpHeaders
个对象中包装标题,因为接受的类型已经过载了)