我在提供者中有一个方法
getProfile() {
let headers = new Headers();
this.loadToken();
headers.append('Authorization', this.authToken);
headers.append('Content-Type','application/json');
return this.http.get(this.db_url + 'profile',{headers: headers})
.map(res => res.json());
}
我在另一个提供程序中调用上述方法
getProfile() {
this.authService.getProfile().subscribe((profile: any) => {
this.profile = profile.user._id;
},(err : any) => console.log(err))
}
在这里,我想停止执行代码,直到执行 this.profile = profile.user._id
这行代码。在我声明的同一个 provider
中getProfile()
方法,我的 http 请求为
let headers = new Headers();
headers.append('Content-Type','application/json');
let selected = {
address: home.address,
date: new Date(),
id: this.profile // from the getProfile() file.
}
console.log(选定);
id
的输出是undefined
。我认为这里有一个异步。
最佳答案
将此代码放入类似的函数中
setHeadres(){
let headers = new Headers();
headers.append('Content-Type','application/json');
let selected = {
address: home.address,
date: new Date(),
id: this.profile // from the getProfile() file.
}
}
并在 getProfile()
函数中调用此函数,如下所示
getProfile() {
this.authService.getProfile().subscribe((profile: any) => {
this.profile = profile.user._id;
this.setHeaders();
},(err : any) => console.log(err))
}
关于javascript - 等待 Ionic 中的订阅方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53683772/