轮询端点并创建结果的可观察结果

时间:2016-03-25 08:10:47

标签: angular rxjs

我有一个端点/user/?is_active=1,它给了我以下回复

{ count: 123,
  next: "next_page_url",
  previous: null,
  results: [
     {id: 323, name: "test"},
     {id: 324, name: "test2"},
     {id: 336, name: "test3"},
     {id: 328, name: "test4"},
  ]
}

我的目标是显示活跃用户数,并通过在端点上轮询每60秒更新一次数据(目前没有套接字...)。 我有一个组件TestComponent,它使用服务UserService

@Component {
   selector: 'test',
   pipes: [Async],
   template: `<div>{{totalActiveUsers}}</div>`,
}
export class TestComponent {
   public totalActiveUsers;
   constructor(userService: UserService) {
      userService.activeUser.subscribe(data => {
         this.totalActiveUsers =  data.count;
      })
   }
}

UserService看起来像这样

import {Http} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import {Users} from './user';

@Injectable()
export class UserService {
    public acitveUser: Observable<Users> = new Observable()
    constructor(private _http: Http) {

    }
    getActiveUser() {
       return this._http.get('/user/?is_active=1').map(res => res.json())
    }
    ...
    //incomplete
}

我想每隔60秒轮询一次enpoint,UserService.activeUserobservable我可以订阅的,每次我有新的活跃用户列表时都会给我回复。

1 个答案:

答案 0 :(得分:2)

您可以这样使用可观察的interval运算符:

export class TestComponent {
  public totalActiveUsers;
  constructor(userService: UserService) {
    Observable.interval(60000).flatMap(() => {
      return this.service.getActiveUser();
    }).subscribe((activeUsers) => {
      this.totalActiveUsers =  data.count;
    });
  }

  (...)
}