[英]Does ngrx/data provide a way to define a custom base API path for my DefaultDataService and then reference that path?
I'm using Angular 13 with NgRx/data and entities (v 13).我正在使用 Angular 13 和 NgRx/数据和实体(v 13)。 I have defined the following data service, in which I wish to override the URL used to retrieve entities...我已经定义了以下数据服务,我希望在其中覆盖用于检索实体的 URL...
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).如果我覆盖另一种方法,我不希望对基础 URL、“http://localhost:8081/myapi/”进行两次硬编码(一次在getAll()
中,一次在另一种方法中)。 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? NgRx/data 是否允许我为该服务定义一个自定义基础 URL,然后我可以在后续的服务调用中引用它?
I like to suggest this approaches,我喜欢建议这种方法,
environment.ts环境.ts
export const environment = {
production: false
url: http://localhost:8081/myapi/
};
environment.prod.ts环境.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
用法:您可以轻松地将environment
导入每个服务,也可以通过与Interceptor
结合使用来使其更先进
* .service.ts * .service.ts
getAll(): Observable<FinanceCustomer[]> {
return this.http.get(environment.url + 'myobjects').pipe(
map((response: any) => {
...
return data;
})
);
}
* .interceptor.ts * .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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.