2017-09-14 79 views
4

我嘗試顯示項目列表(分頁)的一部分。 我的模板:顯示地圖後可觀察

<div class="notif" *ngFor="let notif of paginate() | async"> 
    {{notif.name}} 
</div> 

在我的組件,如果我做的:

public notifications: Observable<Notification[]>; 
public paginate(): Observable<Notification[]> { 
    return this.notifications; 
    } 

這是工作,但如果我這樣做:

public notifications: Observable<Notification[]>; 
public paginate(): Observable<Notification[]> { 
    return this.notifications.map((notif: Notification[]) => { 
    return notif; 
    }); 

它不工作了(I」已經簡化了功能以理解發生了什麼)。 .map回收一個可觀察的權利?所以它應該兩種方式工作?

+0

yap!它應該同時工作,可能做了一些愚蠢的錯誤,並且可觀察部分看起來不錯 –

+0

你得到的錯誤/行爲是什麼? –

+0

在第一種情況下,我看到通知名稱,在第二種情況下,什麼也沒有發生,頁面上沒有顯示 – Lempkin

回答

0

這是錯誤的,因爲您試圖在返回通知Observable []的函數中返回Notification [],所以不起作用。 如果您需要通知[],那麼您需要訂閱Observable。

您無法將Observable映射到其他類型。

例如

public paginate(): Observable<Notification[]> { 
    return this.notifications; 
    }); 


notificationArr: Notification[]; 

// This needs to be inside a method not in the class declaration of variables and methods 
paginate().subscribe((notif: Notification[]) => { 
return (this.notificationArr = notif); 

    }); // should populate your array 
+0

不要忘記通常在ngOnDestroy() – Clyde

+1

.map()期間退訂,並返回一個Observable,對吧?正如他們在這裏所說:http://reactivex.io/documentation/operators/map.html我的目的是通過使用|模板中的異步。所以我嘗試獲取我的通知列表的一部分,但仍返回可觀察值。用map()或filter()不可能? – Lempkin

+0

由於使用'async',我們不需要訂閱。此外,我們不能在課堂上編寫聲明。 – Skeptor