Reputation: 19090
I'm using Angular 13 with NgRx/data and entities (v 13). I have defined the following data service, in which I wish to override the URL used to retrieve entities ...
export class MyObjectService extends DefaultDataService<MyObject> {
...
getAll(): Observable<FinanceCustomer[]> {
return this.http.get('http://localhost:8085/myapi/myobjects').pipe(
map((response: any) => {
...
return data;
})
);
}
This all works well but I'm curious if I can clean this up a little. If I override another method, I would prefer not to hard-code the base URL, "http://localhost:8081/myapi/" twice (once in getAll()
and once in the other method). Is there somewhere where NgRx/data allows me to define a custom base URL for the service, and then I can reference that in subsequent service calls that I'm overriding?
Upvotes: 3
Views: 354
Reputation: 1735
I like to suggest this approaches,
environment.ts
export const environment = {
production: false
url: http://localhost:8081/myapi/
};
environment.prod.ts
export const environment = {
production: true
url: https://api-name.com/myapi/
};
usage:
You can easily import environment
to each service or you can make it more advance by combine with Interceptor
*.service.ts
getAll(): Observable<FinanceCustomer[]> {
return this.http.get(environment.url + 'myobjects').pipe(
map((response: any) => {
...
return data;
})
);
}
*.interceptor.ts
export class APIInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const newReq = req.clone({ url: `${environment.url}/${req.url}` });
return next.handle(newReq);
}
}
Upvotes: 5