2017-06-14 51 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 
    }); 
});