3

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?

paranaaan
  • 1,626
  • 2
  • 9
  • 17
Dave
  • 15,639
  • 133
  • 442
  • 830

1 Answers1

5

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);
  }
}
paranaaan
  • 1,626
  • 2
  • 9
  • 17
  • Thanks but doesn't ngrx/data's DefaultDataService have a way of defining the root base URL it uses? I could just define it there and that would prevent my having to define an interceptor, no? – Dave Aug 25 '22 at 13:21
  • This might answer your case https://stackoverflow.com/a/61917634/11634381 – paranaaan Aug 26 '22 at 00:45
  • Thanks. The answer you linked to says "Currently there's a configuration key that changes prefix of API, but it doesn't allow to specify endpoints per entity" but I notice it is also over 2 years old. Is this still the case? – Dave Aug 30 '22 at 17:23