Emile Cantero
Emile Cantero

Reputation: 2063

Observavable combined with a setTimeout in Angular 4

anybody knows if it is possible to set a Timeout on an http request using Observable, see my code bellow, what I would like is: as soon as my datas are changed in my web API (or backend server) I want to refresh my datas in the view, then the user could know something new is happening...hope I am clear enough...if you don't understand please ask... Or another possibility is: every minute a function could make a new call to the server to check if there is some changes..

  export interface User {
 name: any[];
 data: any[];   
  }

 const userURL = 'http://my.apiserver.com';



@Injectable()
export class UserService {



 users: Observable<User[]>
    constructor (public http:Http) {
         this.users = http.get(usersURL)
                  .retry(3)  
                  .map(res => [res.json()]);

 }

Upvotes: 0

Views: 3175

Answers (2)

Deblaton Jean-Philippe
Deblaton Jean-Philippe

Reputation: 11397

Maybe you can start with that

  private dataState = 'NotInitialized';
  private data = new BehaviorSubject<myObject>(null); // You can also use an empty object instead of null => to avoid null reference exceptions in your calling code


  getMyObject(): Observable<MyObject> {
    if (this.dataState === 'NotInitialized'){
      this.dataState = 'Initialized';

      setInterval(() => {
          this.http.get('myUrl')
           .map(res => res.json())
           .do(res => this.data.next(res))  // Maybe you can check if object has changed
           .subscribe(res => console.log(res)); // Subscribe is important! => otherwise, there is no consumption of this observable
      }, 1000); 

    }

 return this.data;
}

Upvotes: 0

Meir
Meir

Reputation: 14395

You can use timer and switch operators:

this.users = Observable.timer(1000)
  .switch(() => http.get(usersURL).retry(3))
  .map(res => [res.json()])

Upvotes: 1

Related Questions