我试图使用Angular 7在get请求中传递标头。标头是授权令牌。我只是尝试执行以下操作
this.http.get('url', {Authorization: 'Basic xzeydyt=='});
我现在遇到以下错误
'{Authorization:string;类型的参数}'不可分配给类型'{headers ?: HttpHeaders | {[header:string]
答案 0 :(得分:2)
您可以使用这种方法来实现这一点,
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
};
示例 GET 请求
addBook (book: Book): Observable<Book> {
return this.http.get<Hero>(this.bookUrl, httpOptions)
.pipe(
catchError(this.handleError('addBook', book))
);
}
答案 1 :(得分:1)
您将需要创建HttpHeaders
的新实例,并将其传递到get
方法的参数上。
您还需要导入HttpHeaders
才能使用它
import { HttpHeaders } from '@angular/common/http';
因此,您将按照以下步骤构建标题:
let headers = new HttpHeaders();
headers = headers.set('Authorization', 'Basic xzeydyt==');
然后可以将其传递给get方法,如下所示:
this.http.get('url', { headers: headers });
答案 2 :(得分:1)
通过将标头定义为HttpHeaders类型的对象,可以在api请求中添加标头 您的示例:
import { HttpHeaders } from '@angular/common/http';
`const httpHeaders = {headers: new HttpHeaders({
Authorization: 'Basic xzeydyt=='
})
};
this.http.get('url',httpHeaders);`
答案 3 :(得分:1)
示例1:
// Example Get request
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'token'
})};
get_data (): Observable<any> {
const Url = `${serviceurl}`;
return this.http.get<any>(Url, httpOptions)
.pipe(map(res => res))
.catch(err => err);
}
示例2:
// Example Post request
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'token'
})};
Post_data (customer_name): Observable<any> {
const Url = `${serviceurl}`;
const body = JSON.stringify(
{
customer_name: customer_name
});
return this.http.post<any>(Url, body, httpOptions)
.pipe(map(res => res))
.catch(err => err);
}
答案 4 :(得分:0)
我有一个用于以下问题的示例代码。
public getAll() :Observable<employee[]> {
const url = "http://localhost:8080/getAll";
const headers = new HttpHeaders({
Authorization: "Basic " + btoa("user:secret123")
});
return this.http.get<employee[]>(url, { headers });
}
希望它能起作用!
答案 5 :(得分:0)
您需要像这样加强标头。
import { Http, RequestOptions, Headers } from '@angular/http';
这是您获取请求的功能代码
let headers = new Headers({Authorization: 'Basic xzeydyt=='});
let options = new RequestOptions({ headers: headers });
this.http.get(url, options)
.map(data => {
});