I am in need of a service that can both return an observable and set a value to a field within the same method.
The current implementation of my userService.getUserDetails()
method is as follows:
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;
}
When calling getUserDetails
, I aim to achieve two objectives:
1) Return Observable<User>
2) Set the name
value for later access in other classes by injecting this service without re-triggering the http request. This is what I envision:
getName() {
return this.name;
}
However, I am uncertain about using subscribe because I encounter undefined values when attempting to use the stored value. What would be the most appropriate approach to tackle this issue?