2016-07-30 74 views
0

我有一個返回值Observable<Person[]> AA功能,人是我的模型:無法檢索可觀測值

export interface Person { 
    id: string; 
    age: number; 
} 

現在在我的component.ts即時通訊調用這個函數,我想檢索數組,所以我可以顯示它在html中。

該回來示例陣列:

[{"id":"13434 1","age":21},{"id":"34334 1","age":27}] 

我有2個按鈕調用相同的功能。

我在我的component.ts中有三個方法,當點擊按鈕時觸發,這是我想設置一些變量來保存該Observable的返回值。我心中已經盡力去做,但它沒有工作......

這是功能:

@Injectable() 
export class MyCmp implements OnInit { 

    listOneData: Observable<Person[]>; 
    listTwoData: Observable<Animal[]>; 

    showListOne = false; 
    showListTwo = false; 

    constructor(private _myService: MyService) { 
    }; 

    public showListOneData(): void { 
    this.showListOne = true; 
    this.showListTwo = false; 
    this._myService.getListOneData().subscribe(res => { 
     this.listOneData = res; 
    }) 
    } 

    public showListTwo(): void { 
    this.showListTwo = true; 
    this.showListOne = false; 
    this._myService.getListTwoData().subscribe(res => { 
     this.listTwoData = res; 
    }) 
    } 
} 

this.listTwoData = res;這行不能編譯,其由於IM分配Person[]listOneData: Observable<Person[]>;,但即使我走Observable <> it dosent work。

有人可以請我解釋一下什麼是可行的方法嗎?我不想這樣做async因爲我想發送一個數組到html,並基於代碼我應該在哪裏取消訂閱?

謝謝分配!

回答

0

聽起來像你想要兩個不同的東西;從可觀察和認購對象數據,因此可以退訂:

@Injectable() 
export class MyCmp implements OnInit { 

    listOneData: Person[]; 
    listTwoData: Animal[]; 

    listOneSubscription: Subscription;  
    listTwoSubscription: Subscription; 

    showListOne = false; 
    showListTwo = false; 

    constructor(private _myService: MyService) { 
    }; 

    public showListOneData(): void { 
    this.listOneSubscription = this._myService.getListOneData().subscribe(res => { 
     this.showListOne = true; 
     this.showListTwo = false; 
     this.listOneData = res; 
    }) 
    } 

    public showListTwo(): void { 
    this.listTwoSubscription = this._myService.getListTwoData().subscribe(res => { 
     this.showListTwo = true; 
     this.showListOne = false; 
     this.listTwoData = res; 
    }) 
    } 
} 

然後,無論你想退訂:

this.listOneSubscription && this.listOneSubscription.unsubscribe(); 
this.listTwoSubscription && this.listTwoSubscription.unsubscribe(); 

你也提到你不想做異步;這在JavaScript中是沒有意義的,因爲這個異步;問問自己,在內容加載時,你想向用戶展示什麼?您可能想展示某種進度指示器,因此應該將其嵌入到您的視圖中。