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 = {authorization: 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJzYXNobyIsImF1dGgiOiJST0xFX1VTRVIiLCJleHAiOjE1MjQwODcyMzJ9.MUv5RgI9LxQyrrCfjfX8HR2-XiQmz4vjLqH7V_0Du7VFLC0WrK_y3FfeNoT2Nj_uguIK2ss7jv-LNiHuCGtz4A'};
this.http.get('http://localhost:8080/links/all', headers)
.subscribe((e) => {
console.log(e);
}, (err: HttpErrorResponse) => {
console.log(err);
});
}
}
在http.get
中如何设置授权?我想使用保存在 const headers
中的不记名 token 。就这样。谢谢
编辑:我忘了提及,我想知道如何在这里手动设置它而不是使用拦截器,所有教程都带有拦截器,所以我无法弄清楚
最佳答案
试试这个:
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);
});
}
}
关于javascript - Angular 在 HttpClient.get header 中设置授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49894036/