【问题标题】:ionic 2 returning {"__zone_symbol__state":null,"__zone_symbol__value":"cyprus"}离子 2 返回 {"__zone_symbol__state":null,"__zone_symbol__value":"cyprus"}
【发布时间】:2017-11-20 15:51:09
【问题描述】:

我在一个名为 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);
                }); 
        })

    }

当我在另一个 page.ts 中调用此函数以在我的个人资料中获取城市时,它会返回:

{"__zone_symbol__state":null,"__zone_symbol__value":"塞浦路斯"}

这就是我在 page.ts 中的称呼

CityInProfile(){ 控制台.log (JSON.stringify(this.jobsServiceProvider.getCityInProfile())+ '回来') this.cityProfile=this.jobsServiceProvider.getCityInProfile(); }

值在那里(塞浦路斯),但为什么以这种方式返回

【问题讨论】:

    标签: angular typescript cordova ionic2 ionic3


    【解决方案1】:

    您必须记住,服务以异步方式获取数据,因此您必须等待数据准备好。

    如果您不介意,我会对您的代码进行一些小改动:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-24
      • 2015-06-20
      • 2017-09-13
      相关资源
      最近更新 更多