我有一個邏輯問題,我不能解決與可觀察時,它感覺可以。這是(我預計)工廠模式的一部分?發送observable而對象不instanciate
問題是: - 我有一個類'C1'與參數'p'。 - 在'Cl'構造函數中,我發出一個http請求來獲得p的正確值(是的,這部分也感覺很奇怪) -'Cl'有一個返回'p'或其一部分的getter。
當我做instance = new CL(); instance.get();
當然我的http請求尚未完成。所以'p'是未定義的。 只有當p越來越定義時,getter才能返回一個只能接受的觀察值嗎?
也許有些代碼更好地解釋這種情況:
import {lot of thigs } from '@angular/core'; //and RxJs
@Component({
//...
})
export class aClass {
private p:any
constructor() {
this.p = return this.Http.get('a/route')//let's say this request take AGE
.map((response) => {
return response.json();
});
}
//Obviously no working cause cause p isn't "define yet"
public getP(index){
return this.p[index];
}
//I'd hope something like this would work but it doesn't.
public getObservableP(index): Observable<any>{
return Observable.of(this.p[index]);
}
}
你能告訴我如何返回可觀察到的(或者如果它應該是一個承諾)當p爲實例化,請其將滿足。謝謝。
(我已經閱讀了有關http請求在構造函數中的幾件事情是不好的,也許我的想法在這裏是錯誤的)。
首先承諾的是異步所以在你的模板我們?檢查承諾是否完成。 第二次嘗試保存承諾。 this.p =響應; 第三個可能會爲this.p做一個getter。 – Swoox
@Swoox對不起,我讀了兩遍,但我不明白這一點。 – ssbb
您嘗試返回不存在的對象。導致你的申請更快,那麼你的承諾。確實是 – Swoox