【发布时间】:2020-04-13 07:29:05
【问题描述】:
我正在尝试将值形式 localStorage() 设置到我的变量中并在函数中使用该变量,但该变量以 undefined 的形式出现
代码
export class DashboardService {
public token: any;
constructor(
private env: EnvService,
private http: HttpClient,
private storage: NativeStorage
) {
this.storage.getItem('token').then((token) => {
this.token = token.access_token;
console.log('storage token ', token.access_token); // see screenshot below
}).catch(error => console.error(error));
}
getDashboard() {
const headers = new HttpHeaders({
Accept: 'application/json, text/plain',
'Content-Type': 'application/json',
Authorization: this.token
});
console.log('my token ', this.token); // see screenshot below
console.log('my headers ', headers); // see screenshot below
return this.http.get(this.env.Dashboard + '/dashboard', {headers})
.pipe(
tap(data => {
console.log(data);
})
);
}
}
截图
另一个问题是我的请求标头在标头中发送 2 个值而不是 3 个(不确定是不是因为令牌未定义)
它应该发送Accept,Content-Type,Authorization,而不是只发送Accept和Content-Type
有什么想法吗?
更新
这是我在上面调用我的服务的组件
export class DashboardPage implements OnInit {
schools: any = [];
constructor(
private authService: AuthenticationService,
private menu: MenuController,
private dashboardService: DashboardService
) {
this.getSchool();
}
ngOnInit() {
this.menu.enable(true);
}
logout() {
this.authService.logout();
}
getSchool() {
this.dashboardService.getDashboard().subscribe((res) => {
this.schools = res;
});
}
}
【问题讨论】:
-
似乎无法获得以下值:` this.env.Dashboard ` 记录它
-
@xdeepakv 也许,但我最重要的问题是为什么
console.log('my token ', this.token);返回undefined而我在console.log('storage token ', token.access_token);中检查它存在? -
在调用
getDashboard方法时,this.token未定义。存储令牌的构造函数中的调用是异步的。 -
你必须调用
getDashboard方法之后承诺已经解决。您可能需要重组代码以获得所需的效果。也可以考虑使用async / await。您能否也分享一下您调用getDashboard方法的代码 -
@YAS_Bangamuwage 可以,但后来当我向我的服务添加新函数时,我需要在每个函数中调用它.
标签: javascript angular ionic-framework