2017-08-31 90 views
0

服務實際上從服務器獲得正確的值(例如1或0),但在組件中實現服務時總是返回未定義的值。我認爲return聲明剛好在.then()編譯之前編譯。我該如何解決這個問題?此方法總是返回一個未定義的值

private isDuplicateNik(nik: number): boolean{ 
    let count: number; 
    this.employeeService.isDuplicateNik(nik).then(
     res => { 
      count = res; 
     } 
    ); 

    return (count > 0 ? false : true); 
} 
+0

[承諾後的返回值]的可能重複(https://stackoverflow.com/questions/22951208/return-value-after-a-promise) – jonrsharpe

回答

0

最簡單的方法:

private isDuplicateNik(nik: number): Promise<boolean>{ 
    return this.employeeService.isDuplicateNik(nik).then(res => res < 0 ? false : true); 
} 

而且更簡單:

private isDuplicateNik(nik: number): Promise<boolean>{ 
    return this.employeeService.isDuplicateNik(nik).then(res => res > 0); 
} 

然後你使用它像:

this.isDuplicateNik(...).then(res => { 
    console.log("Res: ", res); 
}); 
+0

不幸的是,我仍然得到一個未定義的輸入 –

+0

也返回了一個錯誤'類型無形不能分配到類型布爾',所以我要刪除':布爾' –

+0

我已經更新了答案(類型不匹配)。你確定this.employeeService.isDuplicateNik(nik)返回一個承諾嗎?嘗試通過執行以下操作登錄您所得到的內容: this.employeeService.isDuplicateNik(nik).then(res => console.log(res)); – Faly

0

因爲employeeService是一個異步函數。計數將返回時不確定。

private isDuplicateNik(nik: number) { 
    let subject = Subject(); 
    this.employeeService.isDuplicateNik(nik).then(
     res => { 
      subject.next(res > 0 ? false : true); 
     } 
    ); 

    return subject; 
} 

用作:

this.isDuplicateNik.subscribe(res => console.log(res)); 
+0

返回錯誤'通用類型主題必需1個類型參數' ,'Type Promise is not assignable to type boolean' –

+0

對不起,我沒有看到你給函數返回類型。只要刪除它。 – Carsten