How do I force a refresh on an Observable service in Angular2?

北城以北 提交于 2019-12-17 15:34:25

问题


In ngOnInit, my component obtains a list of users like so:

this.userService.getUsers().subscribe(users => {
    this.users = users;
});

And the implementation of userService.getUsers() looks like this:

getUsers() : Observable<UserModel[]> {
    return this.http.get('http://localhost:3000/api/user')
                    .map((res: Response) => <UserModel[]>res.json().result)
                    .catch((error: any) => Observable.throw(error.json().error || 'Internal error occurred'));
}

Now, in another component, I have a form that can create a new user. The problem is that when I use that second component to create a user, the first component doesn't know that it should make a new GET request to the backend to refresh its view of users. How can I tell it to do so?

I know that ideally I'd want to skip that extra HTTP GET request, and simply append the data the client already has from when it made the POST to insert the data, but I'm wondering how it'd be done in the case where that's not possible for whatever reason.


回答1:


In order for an observable to be able to provide values after initial Http observable was completed, it can be provided by RxJS subject. Since caching behaviour is desirable, ReplaySubject fits the case.

It should be something like

class UserService {
  private usersSubject: Subject;
  private usersRequest: Observable;
  private usersSubscription: Subscription;

  constructor(private http: Http) {
    this.usersSubject = new ReplaySubject(1);
  }

  getUsers(refresh: boolean = false) {
    if (refresh || !this.usersRequest) {
      this.usersRequest = this.http.get(...).map(res => res.json().result);

      this.usersRequest.subscribe(
        result => this.usersSubject.next(result),
        err => this.usersSubject.error(err)
      );
    }

    return this.usersSubject.asObservable();
  }
  onDestroy() {
    this.usersSubscription.unsubscribe();
  }
}

Since the subject already exists, a new user can be pushed without updating the list from server:

this.getUsers().take(1).subscribe(users => 
  this.usersSubject.next([...users, newUser])
)



回答2:


The way I've handled this problem so far has been to use an intermediary. this.userService.getUsers() returns an Rx.BehviorSubject which is initialized on the return of the http observable.

Something close to this:

getUsers() : BehaviorSubject<UserModel[]> {
  return this.behaviorSubject;
}
updateUsers() {
    this.http.get('http://localhost:3000/api/user')
                    .map((res: Response) => <UserModel[]>res.json().result)
                    .catch((error: any) => Observable.throw(error.json().error || 'Internal error occurred'))
                    .subscribe((value) => {
                      this.behaviorSubject.next(value)});
}


来源:https://stackoverflow.com/questions/40249629/how-do-i-force-a-refresh-on-an-observable-service-in-angular2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!