Angular 2 Rxjs:在对象上应用distinct
我有以下对象的obeservable:Angular 2 Rxjs:在对象上应用distinct,angular,rxjs,rxjs5,Angular,Rxjs,Rxjs5,我有以下对象的obeservable: { id : "f3055770-6e66-4936-8e9a-732b53121549" message:"Empty Notification for test ......" navigationLink:"/fusion/home" seen:false sendedOn:"2016-12-02T15:19:44.856Z" userId :nul
{
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
Serveur原始响应:
"[{"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"}]"
我找到了独特的解决方案 事实上,传递给disctinct的函数可以接受2个参数(PreventValue、actualValue),因此您可以这样解决此问题:
....
....
.distinct(function (x, y) { return x.id === y.id; });
它在每次迭代时返回一个布尔值(x.id=y.id?=>true或false…)
**更新**
我的错误是我在寻找rxjs 4.0文档,而我的项目在rxjs 5上。请给出上下文:1)如何调用此方法?2) 您在哪里添加
distinct
操作符?您确定这四个对象没有相同的id
?更新@martin yeah am shure,id不是same@NacimIdjakirene在将原始响应传递给.json()
)之前,能否显示服务器的原始响应?请参阅更新的问题