noo*_*oor 2 cordova typescript ionic2 ionic3 angular
我在一个名为api-serive.ts的提供者页面中有我的功能
//get city in profile
getCityInProfile(){
return new Promise((resolve, reject) => {
let headers = new Headers({ 'Authorization':
localStorage.getItem('token') });
this.http.get(this.getProfile,{headers:headers}).subscribe(
(res) => {
console.log (res.json().profile.location)
resolve(res.json().profile.location)
return (resolve(res.json().profile.location));
},(err) => {
reject(err);
});
})
}
Run Code Online (Sandbox Code Playgroud)
当我在另一个page.ts中调用此函数来获取我的个人资料中的城市时,它会返回:
{ "__zone_symbol__state":空, "__ zone_symbol__value": "塞浦路斯"}
这就是我在page.ts中调用它的方式
CityInProfile(){console.log(JSON.stringify(this.jobsServiceProvider.getCityInProfile())+'return')this.cityProfile = this.jobsServiceProvider.getCityInProfile(); }
价值在那里(塞浦路斯),但为什么它会以这种方式返回
您必须记住,服务是以异步方式获取数据,因此您必须等待该数据准备就绪.
如果您不介意,我会对您的代码进行一些小的更改:
// Get city in profile
getCityInProfile(): Promise<any> {
// First get the token from the localStorage (it's async!)
return localStorage.getItem('token').then(token => {
// Set the token in the header
let headers = new Headers({ 'Authorization': token });
// Make the request, but don't subscribe here!
return this.http.get(this.getProfile, { headers:headers })
.map(res => res.json())
.map(resJson => resJson.profile.location)
.toPromise();
});
}
Run Code Online (Sandbox Code Playgroud)
然后,当您想要使用该服务时,您需要这样做:
public getCityInProfile(): void {
// Use the 'then' to wait for the response to be ready
this.jobsServiceProvider.getCityInProfile().then(city => {
// Now you can use the city returned by the service
console.log(`Returned: ${city}`);
this.cityProfile = city;
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5590 次 |
| 最近记录: |