Observavable 与 Angular 中的 setTimeout 相结合 4

Observavable combined with a setTimeout in Angular 4

有人知道是否可以使用 Observable 在 http 请求上设置超时,请参阅下面的代码,我想要的是: 一旦我的 web API(或后端服务器)中的数据发生更改,我想在视图中刷新我的数据,然后用户就会知道发生了新的事情......希望我足够清楚......如果你不明白请问...或者另一种可能性是:每分钟一个函数可以对服务器进行新的调用以检查是否有一些变化..

  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()]);

 }

您可以使用 timer and switch 运算符:

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

也许你可以从那个开始

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