NxRx-Data自定义DataService没有使用DataSeviceConfiguration

NxRx-Data custom DataService does not use DataSeviceConfiguration

我这样扩展了 DefaultDataService:

    @Injectable()
    export class DidDocumentDataService extends DefaultDataService<DidDocument> {
      constructor(http: HttpClient, httpUrlGenerator: HttpUrlGenerator) {
        super("DidDocument", http, httpUrlGenerator, defaultDataServiceConfig);
      }

      getById(): Observable<DidDocument> {
        return this.http.get("/identifiers").pipe(
          map(res => res["didDocument"])
        );
      }
    }

app-store.module.ts 设置如下:

// this used to work before overriting the DefaultDataService
export const defaultDataServiceConfig: DefaultDataServiceConfig = {
  root: `${HOST}/1.0/`
};

@NgModule({
  imports: [
    EntityDataModule.forRoot(entityConfig),
    ... // other store related imports
  ],
  providers: [
    DidDocumentDataService,
    { provide: DefaultDataServiceConfig, useValue: defaultDataServiceConfig }
  ],
  declarations: [StoreComponent],
  exports: [StoreComponent]
})
export class AppStoreModule {
  constructor(
    private entityDataService: EntityDataService,
    private didDocService: DidDocumentDataService
  ) {
    this.entityDataService.registerService("DidDocument", this.didDocService);
  }
}

在我扩展 DefaultDataService 之前,使用了 defaultDataServiceConfig 并且针对自定义 root 触发了请求。现在每个请求都命中 localhost(似乎只使用当前主机)。

AppStoreModule 不是惰性加载模块,在 AppModule 中加载。触发请求的组件是 StoreComponent。我的第一个猜测是事情没有按照我预期的顺序发生。

CustomDataServiceCustomConfiguration 何时创建,覆盖服务是否仅在延迟加载模块中有效?

解决方案

我直接在httpClient中设置了绝对值URL,同时也将identiefer传给了getById方法:

getById(id: string): Observable<DidDocument> {
  return this.http.get(`${HOST}/1.0/identifiers/${id}`).pipe(
    map(res => res["didDocument"])
  );
}

您的问题的根本原因可能在这段代码中:

getById(): Observable<DidDocument> {
  return this.http.get("/identifiers").pipe(
    map(res => res["didDocument"])
  );
}

在这种情况下,即使 DefaultDataServiceConfig 使用正确的 url 正确设置,此代码也会覆盖 GET url。

http.get("/identifiers")

等同于

http.get("http://localhost/identifiers")

(如果您的开发应用程序在 localhost 上运行)

您应该设置绝对值 url 或将 DefaultDataService 的祖先方法与 super 一起使用:

getById(): Observable<DidDocument> {
  return super.getById(id).pipe(
    map(res => res["didDocument"])
  );
}

您可以在 official doc 中找到更多详细信息,使用以下代码片段示例:

@Injectable()
export class HeroDataService extends DefaultDataService<Hero> {
  constructor(http: HttpClient, httpUrlGenerator: HttpUrlGenerator, logger: Logger) {
    super('Hero', http, httpUrlGenerator);
    logger.log('Created custom Hero EntityDataService');
  }

  getById(id: string | number): Observable<Hero> {
    return super.getById(id).pipe(map(hero => this.mapHero(hero)));
  }
}