我试图点击API来执行一个非常简单的get
请求,但由于我收到身份验证错误,因此选项似乎没有提供,即使相同的身份验证令牌适用于Postman。这是代码:
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable()
export class UsersService {
private nearby_url: string = APP_CONFIG.apiEndpoint + '/users/closest/';
private me_url: string = APP_CONFIG.apiEndpoint + '/users/me/';
private conversations_url: string = APP_CONFIG.apiEndpoint + '/users/conversations/';
constructor(private http: HttpClient) { }
createAuthorizationHeader() {
var headers = new HttpHeaders();
// get auth token
// append auth token to headers
headers.append("Authorization", 'Token xxxxxxxxxxxyyyyyyyyyyyyzzzzzzzzz');
return headers
}
getPersonResponse(url): Observable<PersonResponse> {
const options = {
headers: this.createAuthorizationHeader()
};
return this.http.get(url, options)
.map((response: Response) => response)
.catch((error: any) => Observable.throw(error.error || 'Server error'));
}
getNearby(): Observable<PersonResponse> {
return this.getPersonResponse(this.nearby_url);
}
getMe(): Observable<PersonResponse> {
return this.getPersonResponse(this.me_url);
}
getConversations(): Observable<PersonResponse> {
return this.getPersonResponse(this.conversations_url);
}
}
我在这里做错了什么?
答案 0 :(得分:5)
改为
const headers = new HttpHeaders()
.set("X-CustomHeader", "custom header value");
请注意,我们正在通过链接构建HTTPHeaders对象 连续的set()方法。这是因为HTTPHeaders是不可变的, 及其API方法不会导致对象突变。相反,打电话给 set将返回包含新值的新HTTPHeaders对象 属性。
更多相同内容 - https://rahulrsingh09.github.io/AngularConcepts/services