My REST API implementation requires an access token for user identification with each call. If the token is missing or expired, the endpoint returns a 401 UNAUTHORIZED response.
There are instances where I make API calls using a timer in my service class:
getFoo(id: String): Observable<Foo> {
return this.http.get<Foo>(url, HTTP_OPTIONS);
}
getFooList(): Observable<Foo[]> {
return timer(0, FIVE_MINUTES).pipe(
switchMap(() => this.http.get<Foo[]>(url, HTTP_OPTIONS))
);
}
In the component, I initialize an empty array for Foo items and call the loadFooList() method in the ngOnInit() lifecycle hook:
fooList: Foo[] = [];
ngOnInit(): void {
this.loadFooList();
}
private loadFooList() {
this._fooService.getFooList().subscribe(
(fooList) => this.fooList = fooList,
(err) => console.error(err)
);
}
My concern is about handling the 401 response in the service itself rather than in each component that utilizes it. Is there a way to check for a 401 response within the service?