Angular 2 Rxjs:在对象上应用不同

Angular 2 Rxjs : Apply distinct on objects

我有这些对象的可观察值:

  {
        id : "f3055770-6e66-4936-8e9a-732b53121549"
        message:"Empty Notification for test ......"
        navigationLink:"/fusion/home"
        seen:false 
        sendedOn:"2016-12-02T15:19:44.856Z"
        userId :null
      }

我不想收到重复的对象(基于 id),我用这个方法来实现它

 notify(userID: string) {
    return Observable.interval(5000)
        .map(() => this.baseUrl + '/notification/GetUnseen?userId=' + userID)
        .switchMap(url => {
            return Observable.from(this.datatService.get(url));
        })
        .flatMap(response => Observable.from(response.json().slice()))

}

当我添加 distinct(x => x.id) 作为最后一个运算符时,我只有一个对象而不是四个对象有什么帮助吗?

更新:

我在我的组件的 oninit() 生命周期中调用这个方法,这样该方法每 5 秒执行一次以获取通知,我这样使用 distict :

 notify(userID: string) {
    return Observable.interval(5000)
        .map(() => this.baseUrl + '/notification/GetUnseen?userId=' + userID)
        .switchMap(url => {
            return Observable.from(this.datatService.get(url));
        })
        .flatMap(response => Observable.from(response.json().slice()))
        .distinct(x => x.id);
}

更新 2

服务器原始响应:

"[{"userId":null,"sendedOn":"2016-12-02T15:19:44.856Z","message":"Empty Notification for test ......","navigationLink":"/fusion/home","seen":false,"id":"f3055770-6e66-4936-8e9a-732b53121549"},{"userId":null,"sendedOn":"2016-12-02T15:19:45.146Z","message":"Empty Notification for test ......","navigationLink":"/fusion/home","seen":false,"id":"ce172122-11d9-4054-a3e4-594c8c910a7d"},{"userId":null,"sendedOn":"2016-12-02T15:19:45.146Z","message":"Empty Notification for test ......","navigationLink":"/fusion/home","seen":false,"id":"66e32c45-f544-4ce6-901c-e5ac64904954"},{"userId":null,"sendedOn":"2016-12-02T15:19:45.147Z","message":"Empty Notification for test ......","navigationLink":"/fusion/home","seen":false,"id":"4c2322cb-526c-490e-8a86-f1e9ced1c34f"}]"

我找到了不同的解决方案!

事实上,传递给 distinct 的函数可以接受 2 个参数(precedentValue、actualValue),因此您可以这样解决这个问题:

....
....
.distinct(function (x, y) { return x.id === y.id; });

它 return 每次迭代都是一个布尔值(是 x.id = y.id ?=> true 或 false...)。

**更新**

我的错误是我在寻找 rxjs 4.0 文档,而我的项目是在 rxjs 5 上。