首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >返回{"__zone_symbol__state":null,“__zone_symbol__value”:“塞浦路斯”}

返回{"__zone_symbol__state":null,“__zone_symbol__value”:“塞浦路斯”}
EN

Stack Overflow用户
提问于 2017-06-18 09:11:04
回答 1查看 7.4K关注 0票数 2

我的函数位于一个名为api-erive.ts的提供程序页面中。

代码语言:javascript
复制
//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里就是这样称呼它的

{ (JSON.stringify(this.jobsServiceProvider.getCityInProfile() )+‘返回’) this.cityProfile=this.jobsServiceProvider.getCityInProfile();}

价值在那里(塞浦路斯),但为什么要以这种方式归还?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-06-18 09:50:42

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

如果您不介意的话,我会对您的代码做一些小修改:

代码语言:javascript
复制
// 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();

    });
}

然后,当您想要使用该服务时,您需要这样做:

代码语言:javascript
复制
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;

    });

}
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44613463

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档