2017-06-14 117 views
1

我有一个提供商应该允许我从我需要的API返回特定数据。我有这个功能做的:从Javascript提供商承诺函数中返回数据

public getStoryCount(key: string, val: number) { 
    return this.client.getEntries({ 
     'content_type': xxxxxxxxxxxxxx, 
     [key]: val, 
    }).then((entries:any) => { 
     return entries.total; 
    }); 
} 

这是我第一次真正使用的承诺,但我试图调用此组件中的获得的价值。我希望能够获取当我console.log获取输出时的值entries.total。

我建立了一组数据,我认为使用像这样:

this.homeScreen.push({ 
    'count': Provider.getStoryCount('sys.id', xxxx) 
}); 

当我CONSOLE.LOG提供者的功能,我可以看到在承诺的价值,它看起来像这样:

__zone_symbol__state : true 
__zone_symbol__value : 13 // this is the value I need to get 

如何将该数字13保存到我的数组homeScreen ['count'] value?或者我做错了什么?

回答

0

这是一个异步操作。你需要通过一个功能then

Provider.getStoryCount('sys.id', xxxx) 
    .then((total) => { 
    this.homeScreen.push({ 
    'count': total 
    }); 
    }); 
1

您正在返回Promise而不是实际值。这意味着修改您的组件代码为:

Provider.getStoryCount('sys.id', xxxx) 
    .then((entries:any) => { 
     this.homeScreen.push({ 
      'count': entries.total 
     }); 
    } 
}); 

应该工作。

您也可以让您的Provider服务获取该值并将其存储为Observable,以便组件可以订阅该值。

0

首先,要将承诺的结果映射到另一个值,请使用map。

public getStoryCount(key: string, val: number) { 
    return this.client.getEntries({ 
     'content_type': xxxxxxxxxxxxxx, 
     [key]: val, 
    }).map((entries:any) => { 
     return entries.total; 
    }); 
} 

然后,当调用返回的承诺使用功能来then得到结果

Provider.getStoryCount('sys.id', xxxx).then((total) => ...use total...); 
1

由于承诺是异步的,你是不是真的返回entries.total像你想象的。

您可能需要提供自己的回调函数,或者直接返回promise(由this.client.getEntries生成),并在then上添加结果。它可能看起来像这样:

public getStoryCount(key: string, val: number) { 
    return this.client.getEntries({ 
     'content_type': xxxxxxxxxxxxxx, 
     [key]: val, 
    }); 
    // The 'then' will be added later 
} 

// ... 

// Get the promise from the provider, and invoke 'then' here. 
var storyCountPromise = Provider.getStoryCount('sys.id', xxxx); 
storyCountPromise.then((entries:any) => { 
    this.homeScreen.push({ 
     'count': entries.total 
    }); 
});