我正在尝试获取使用离子存储存储的令牌并将其存储在全局变量public token = ''
中。但是每次我使用this.token
该值访问它时都不会改变。
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
const TOKEN_KEY = 'access_token';
@Injectable()
export class ContactProvider {
public url = 'myapi-link';
public token = '';
constructor(
private storage: Storage,
private http: HttpClient
) {
}
loadToken(){
this.storage.get(TOKEN_KEY).then((token)=>{
this.token = token;
console.log(this.token);
});
}
setHeaders(default_content_type = 'application/json'){
let headers = new HttpHeaders();
headers = headers.set('Content-Type', default_content_type)
.set('Authorization', 'Bearer ' + this.token)
return headers;
}
getData(type){
this.loadToken();
let headers = this.setHeaders();
return this.http.get(this.url + type, {headers: headers});
}
}
调用 时this.setHeaders()
,this.token
不会改变。