我正在使用Angular 6设置一些API调用,并使用ngx cookieService来访问和存储cookie。我想从我的API获取访问令牌,并在另一个服务中发送get请求时将其用作标头。这是我的登录服务中的功能:
getData() {
return this.http.post(this.base_URL + "web_app/login/", JSON.stringify(this.login))
.subscribe(response=>{
this.access_token = response['access_token'];
console.log("received token " + this.access_token)
this.cookieService.set( 'access_token', this.access_token );
this.cookieValue = this.cookieService.get('access_token');
console.log("set cookie value" + this.cookieValue);
} }
这是其他服务:
farmAccess(){
let headers = new HttpHeaders();
this.cookieValue = this.cookieService.get('access_token');
headers.append('access_token', this.cookieValue);
console.log("retrieved cookie value" + this.cookieValue);
return this.http.get(this.baseURL + 'web_app/farm_access/', {headers})
.subscribe(
res => console.log(res),
// msg => console.error(`Error: ${msg.status} ${msg.statusText}`
)
};
我将访问令牌存储为cookie,并希望在farmAccess服务中访问它。但是,这不起作用。比较两个cookie,这是控制台上的内容:
这是我调用函数的地方:
ngOnInit(): void {
this.data = this.login.getData();
this.farmAccessdata = this.getFarmAccess.farmAccess();
}
我检查了控制台中的cookie,它显示了access_token的正确值。那么为什么farmAccess服务拉错了价值呢?谢谢你的帮助!
编辑:看起来函数运行不正常。如何让它们按我想要的顺序运行?
答案 0 :(得分:0)
按如下所示更改登录服务功能
ngOnInit(): void {
this.data = this.login.getData().subscribe(response =>{
// Set the token & cookie from the component. Changes access_token ==> login.access_token
// You may also need to inject cookieService in component as well
this.login.access_token = response['access_token'];
console.log("received token " + this.login.access_token)
this.cookieService.set( 'access_token', this.login.access_token );
this.cookieValue = this.cookieService.get('access_token');
console.log("set cookie value" + this.cookieValue);
// Move this call in subscribe method
this.farmAccessdata = this.getFarmAccess.farmAccess();
});
}
组件ngOnInit方法如下:
{{1}}