I have an observable data service (UserService) that returns a registered user. I followed this tutorial - https://coryrylan.com/blog/angular-observable-data-services , which describes how to use a BehaviorSubject to immediately return the currentUser to default, and then release the real currentUser after it is downloaded or modified. The service is basically like that ...
private _currentUser: BehaviorSubject<User> = new BehaviorSubject(new User());
public currentUser: Observable<User> = this._currentUser.asObservable();
constructor(private http: Http) {}
loadUser() { // app.component onInit and login component call this
return this.http.get('someapi.com/getcurrentuser')
.map(response => <User>this.extractData(response))
.do(
(user) => {
this.dataStore.currentUser = user;
this._currentUser.next(Object.assign(new User(), this.dataStore).currentUser);
},
(error) => this.handleError(error)
)
.catch(error -> this.handleError(error));
}
, F5, -. currentUser UserService, , UserService api . , api, UserService, . , BehaviorSubject, "undefined", api. , , , user.id, , .
, - , . concatMap, , . , , . , , , , Observables.
this.userService.currentUser
.flatMap((user) => {
this.user = user;
this.someOtherService.getSomethingElse(user.id);
})
.subscribe((somethingElse) => {
this.somethingElse = somethingElse;
});