我正试图通过以下方式从我的角度服务获取用户信息。
import { Injectable } from '@angular/core';
import {homeUrls} from "../../../utils/urls";
import {Http, RequestOptions, Response} from '@angular/http';
import { Headers } from '@angular/http';
@Injectable()
export class AdsService {
private headers = new Headers({'Content-Type': 'application/json'});
private token: string;
constructor(private http: Http) {
this.token = localStorage.getItem('token');
console.log("token is " , this.token);
this.headers.set('Authorization', 'Token ' + this.token );
console.log("header is");
console.log(this.headers);
this.getMe();
}
getMe(): Promise<any> {
return this.http.get(homeUrls.User, {headers: this.headers})
.toPromise()
.then(res=> {
console.log("user is");
console.log(res.json());
})
}
但我收到了以下错误
无法加载http://127.0.0.1:8000/users/account/me/:预检的响应包含无效的HTTP状态代码401.
当我在网络选项卡中检查时,它显示“未提供身份验证凭据”,尽管我已经设置了授权标头,因为它可以在我的服务构造函数中看到。知道这里有什么问题吗?
答案 0 :(得分:0)
标头是一个不可变对象。 set和append方法不会修改Headers对象,它们会返回一个新的Object。
此外,您可能希望使用append而不是set。