I started doing my project in a module by module basis, so each one had to access the user.
Now that I'm polishing it, I'm having multiple API requests for the same thing (user info).
Much I found on the internet is deprecated and doesn't work anymore (mostly RxJs stuff).
What I have: the callback from the API with the user info. What I want: something shareable globally in the project (I only need one request for the API for the user info)
I'm trying right now to turn an observable into another:
@Injectable({
providedIn: 'root',
})
export class LoginInfoService {
constructor(private http: HttpClient) {}
private userURL = `${environment.API}/loginUser`;
private user$: Observable<LoggedUser>;
private request = false;
public retrieveUser(): Observable<LoggedUser> {
if (!this.request&& !this.user$) {
console.log("call request");
this.user$ = this.getUserJson();
}
return this.user$;
}
private getUserJson() {
console.log('actual request');
this.request = true;
return this.http.get<LoggedUser>(`${this.userURL}?key='123'`);
}
}
I'm using for testing "json-server" and while I get only one 'actual request' printed, the server shows multiple requests there. I'm using the latest stable version of Angular.
You can use shareReplay, the http request will be executed only once then the result will be cached for any new subscription. Also, you can remove the request variable.
@Injectable({
providedIn: 'root',
})
export class LoginInfoService {
constructor(private http: HttpClient) {}
private userURL = `${environment.API}/loginUser`;
private user$: Observable<LoggedUser>;
public retrieveUser(): Observable<LoggedUser> {
return this.user$.pipe(shareReplay(1));
}
private getUserJson() {
return this.http.get<LoggedUser>(`${this.userURL}?key='123'`);
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments