Angular 离子2返回{quot;'uuuu区'u符号'uu状态'quot;:空,'uquot;'uuu区'u符号'uu值'quot;:“塞浦路斯”}
我的函数位于一个名为api-serive.ts的提供程序页面中Angular 离子2返回{quot;'uuuu区'u符号'uu状态'quot;:空,'uquot;'uuu区'u符号'uu值'quot;:“塞浦路斯”},angular,typescript,cordova,ionic2,ionic3,Angular,Typescript,Cordova,Ionic2,Ionic3,我的函数位于一个名为api-serive.ts的提供程序页面中 //get city in profile getCityInProfile(){ return new Promise((resolve, reject) => { let headers = new Headers({ 'Authorization': localStorage.getItem('token') });
//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);
});
})
}
当我在另一个page.ts中调用此函数以获取我个人资料中的城市时,它将返回以下内容:
{“\uuuu区域\u符号\uuuu状态”:null“\uuuu区域\u符号\uuuuu值”:“塞浦路斯”}
这就是我在我的页面中对它的称呼
CityInProfile(){console.log
(JSON.stringify(this.jobsServiceProvider.getCityInProfile())+
“返回”)
this.cityProfile=this.jobserviceprovider.getCityProfile();}
值在那里(塞浦路斯),但为什么以这种方式返回它呢?您必须记住,服务是以异步方式获取数据的,所以您必须等待数据准备就绪 如果您不介意,我会对您的代码做一些小更改:
// 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();
});
}
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;
});
}