0

I have this simple method in my service :

 notify(userID: string) { let _URL = this.baseUrl + '/notification/GetUnseen?userId=' + userID; this.datatService.set(_URL); return this.datatService.get() .flatMap((response) => response.json().slice()) .distinct(); } 

It return a stream of object which contain informations about user's notification. i would like to execute this call every 5 second with interval operator without using setTimeout ?

When i try this :

 notify(userID: string) { let _URL = this.baseUrl + '/notification/GetUnseen?userId=' + userID; this.datatService.set(_URL); return this.datatService.get() **.interval(5000)** .flatMap((response) => response.json().slice()) .distinct(); } 

I have an error. Any Suggestion ?

1 Answer 1

2
notify(userID: string) { return Observable.interval(5000) .map(() => this.baseUrl + '/notification/GetUnseen?userId=' + userID) .switchMap(url => { this.dataService.set(url); return this.dataService.get(); }) .map(response => ....{ <your handler> } } 

A few notes: 1. You must subscribe to the returned value to start the calls. 2. Your data service is statefull, this might create race condition where 2 different clients set the url and then invoke it, consider converting the get to a stateless function: get(url), in which case your code will be

notify(userID: string) { return Observable.interval(5000) .map(() => this.baseUrl + '/notification/GetUnseen?userId=' + userID) .switchMap(url => this.dataService.get(url)) .map(response => ....{ <your handler> } } 
Sign up to request clarification or add additional context in comments.

1 Comment

I'am subscribing to the method in my component, thx for the note about the statfull function +1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.