簡體   English   中英

ngrx/data 是否提供了一種方法來為我的 DefaultDataService 定義自定義基本 API 路徑,然后引用該路徑?

[英]Does ngrx/data provide a way to define a custom base API path for my DefaultDataService and then reference that path?

我正在使用 Angular 13 和 NgRx/數據和實體(v 13)。 我已經定義了以下數據服務,我希望在其中覆蓋用於檢索實體的 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;
          })
        );
      }

這一切都很好,但我很好奇我是否可以清理一下。 如果我覆蓋另一種方法,我不希望對基礎 URL、“http://localhost:8081/myapi/”進行兩次硬編碼(一次在getAll()中,一次在另一種方法中)。 NgRx/data 是否允許我為該服務定義一個自定義基礎 URL,然后我可以在后續的服務調用中引用它?

我喜歡建議這種方法,

環境.ts

export const environment = {
  production: false
  url: http://localhost:8081/myapi/
};

環境.prod.ts

export const environment = {
  production: true
  url: https://api-name.com/myapi/
};

用法:您可以輕松地將environment導入每個服務,也可以通過與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);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM