1

i my angular 2 service i have this method :

  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 });
   }

How can i use the distinct operator with key selector in this cas ? When i try to do it i have this error : Property 'id' does not exist on type '{}'.

UPDATE :

The final result i get with this method is :

  {
  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
  }

I would like to filter the result, so if i already have the notification i dont want to get in again

1 Answer 1

2

I don't know exactly how your data structure looks like, but from the example code I guess that you try to map an array to an Observable sequence with this code part:

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

What you would need to do is create a new Observable sequence with Observable.from and then use switchMap to get it back into the original stream. Then you can use the distinct operator as wished. See this code sample:

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

Sign up to request clarification or add additional context in comments.

3 Comments

Can't get your exemple works in my case, maybe i'am missing something
when i try this : 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); } i have only ONE object instead of four !
it helped me a lot , can you please further explain why we need to create an observable again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.