2017-09-14 48 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