2017-06-18 27 views
2

我有我的供應商頁面功能調用的API-serive.ts離子2返回{ 「__zone_symbol__state」:空, 「__ zone_symbol__value」: 「塞浦路斯」}

//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); 
       }); 
     }) 

    } 

,當我在另一個頁面調用這個函數.TS讓我的個人資料本市它返回:

{「__zone_symbol__state」:空,「__ zone_symbol__value」:「塞浦路斯」}

,這是我怎麼把它在我的網頁.ts

CityInProfile(){的console.log (JSON.stringify(this.jobsServiceProvider.getCityInProfile())+ '返回') this.cityProfile = this.jobsServiceProvider.getCityInProfile(); }

的價值是存在的(塞浦路斯),但爲什麼它返回這樣

回答

2

你必須記住,該服務獲取數據以異步方式所以你必須要等待該數據準備就緒。

如果你不介意的話,我會做一些小的改動你的代碼:

// 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; 

    }); 

} 
+1

非常感謝你! – noor