2016-12-02 75 views
1

我我的角度分2次服我有這樣的方法:Rxjs Angular 2中的按鍵選擇符不同的運算符?

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

如何使用與鍵選擇不同的運營商在這CAS? 當我嘗試這樣做時,我有這個錯誤:類型'{}'上不存在屬性'id'。

UPDATE:

最後的結果我用這種方法得到的是:

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

我想過濾的結果,所以,如果我已經有我不通知想再次獲得

回答

1

我不知道你的數據結構究竟是怎樣的,但從示例代碼我猜你試圖將數組映射到具有此代碼部分的Observable序列:

(...).flatMap(response => response.json().slice()) 

您需要做的是創建一個新的可觀察序列Observable.from,然後使用switchMap將其恢復爲原始流。然後您可以按照希望使用distinct運算符。看到這個代碼示例:

const str = JSON.stringify([{id: 1}, {id: 1}, {id: 2}, {id: 1}]); 

Rx.Observable.of(str) 
    .map(x => JSON.parse(x)) // replication of your sample code until this line 
    .switchMap(x => Rx.Observable.from(x)) 
    .distinct(x => x.id) 
    .subscribe(x => console.log(x)); 

// output: { id: 1 } 
//   { id: 2 } 

Live code on JSBin

+0

無法讓爲例在我的情況下工作,也許我'失去了一些東西 –

+0

當我試試這個: 通知(用戶名:字符串){ 回報Observable.interval(5000) .map(()=> this.baseUrl +'/ notification/GetUnseen?userId ='+ userID) .switchMap(url => { return Observable.from(this.datatService.get url)); }) .flatMap(response => Observable.fro m(response.json()。slice())) .distinct(x => x.id); } 我只有一個對象而不是四個! –

+0

它對我有很大幫助,請您進一步解釋爲什麼我們需要再次創建觀察點 –