2017-08-25 20 views
0

我有一個邏輯問題,我不能解決與可觀察時,它感覺可以。這是(我預計)工廠模式的一部分?發送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請求在構造函數中的幾件事情是不好的,也許我的想法在這裏是錯誤的)。

+0

首先承諾的是異步所以在你的模板我們?檢查承諾是否完成。 第二次嘗試保存承諾。 this.p =響應; 第三個可能會爲this.p做一個getter。 – Swoox

+0

@Swoox對不起,我讀了兩遍,但我不明白這一點。 – ssbb

+0

您嘗試返回不存在的對象。導致你的申請更快,那麼你的承諾。確實是 – Swoox

回答

1

如果代碼貼充當的服務,最好的辦法是利用異步管道是這樣的:

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(); 
    }); 
} 

public getP(index){ 
    return this.p; 
} 
} 

在你的組件,你會注入ACLASS和模板:

<div *ngFor="let something of aClass.getP() | async"> 
    {{something}} 
</div> 

<p>{{aClass.getP() | async}}</p> 
+0

我想這會工作。 可以肯定的是,你是否知道getter是異步的,而不是放在模板中 – ssbb

+0

你需要返回一個observable(就像我寫的)。然後你可以在組件代碼中使用它來訂閱它。假設你有一個注入你的'aClass'服務的組件,並且這個服務有一個getP方法返回你的可觀察值。然後在你的組件中,你可以編寫'this.aClass.getP()。subscribe((result)=> result);'在訂閱塊中,你可以將結果保存到一個變量中,過濾等等。 – Matsura