In my angular application, I want to include the user token in each of my http request, so for what i have learned it is best to create a service so i dont have manually include my token or other parameter each time for my http request. The code could be like this:
export class FacilityService{
constructor(private http: HttpClient) {
}
const httpOptions = {
header: new HttpHeaders({
Authorization: `bearer ` + JSON.parse(localStorage.GetItem('user')).token
})
}
load(): Observable<any> {
return this.http.get<any>(
`${environment.rootUrl}/facility/getFacility`, httpOptions
);
}
}
However, I also learned to use the Service to store state. So we dont have to request from the server each time. The Code could like this:
export class FacilityService{
facility: Facility[] = [];
constructor(private http: HttpClient) {
}
const httpOptions = {
header: new HttpHeaders({
Authorization: `bearer ` + JSON.parse(localStorage.GetItem('user')).token
})
}
load(): Observable<any> {
if(this.facility.length > 0) return of(this.facility);
return this.http.get<any>(
`${environment.rootUrl}/facility/getFacility`, httpOptions
).pipe(map(facility =>
this.facility = facility;
return facility;
));
}
}
2 question:
-
if I suppose to create a local state for all HTTP requests of all my entities? Each time I check the local data first and if it does not exist I request from the server. And I will have facility service, user service, order service.
-
How should I merge all those services into one service so I don't have to create the service for each of my entities? example, users data, and orders data can also share the service
Aucun commentaire:
Enregistrer un commentaire