I want a service that would return the observable and set a value to field in the same method.
Now my userService.getUserDetails() method looks like this:
private requestUrl: string;
private bic: string;
private id: string;
private name: string;
getUserDetails(): Observable<User> {
this.bic = 'aaa';
this.id= '123';
this.requestUrl = `${configs.api}v1/bics/` + encodeURIComponent(this.bic) + `/ids/` + encodeURIComponent(this.id) + `/users`;
const userObservable = this.http.get<User>(this.requestUrl).pipe(catchError(this.handleError));
userObservable.subscribe(data => this.name = data.name);
return userObservable;
}
I want to do two things when getUserDetails is called:
1) return Observable<User>
2) set the name value so I could access it later in other classes by injecting this service in constructors, without calling the http request again. I think I want to have something like this:
getName() {
return this.name;
}
So I'm not sure about the subscribe, because I'm getting undefined after try to use the value. What is the best approach here?
userObservable.subscribe(data => console.log(data));? Observables are asynchronous, which means you should only work with the variable once the observable returned a value.