繁体   English   中英

在 Angular 中注入 URL 6 延迟加载模块之间共享的服务

[英]Inject URL in Angular 6 Service shared across lazy loaded modules

When I created a service shared between two lazy loaded modules with a different injected URL string, the module URL is logged right in the service constructor but not updated in the service function that does HTTP request.

场景:首先我导航到 module1,响应正确返回了 module1 项目,然后我导航到模块,HTTP 请求由 module1 URL 发送所以它返回了错误的项目

共享服务.ts

@Injectable()
export class SharedService {
  constructor(
    private http: HttpClient,
    @Inject('BASE_URL_TOKEN') private url: string
  ) {
console.log(this.url); // prints the right value
}
  getItems(invoiceCode: string): Observable<any> {
   console.log(this.url); // prints the old value
    return this.http.get(
      this.url + RestUrls.ITEMS_URL,
      httpOptions
    );
  }

}

shared.module.ts

export const BASE_URL_TOKEN = 'BASE_URL_TOKEN';

@NgModule({
  imports: [
    CommonModule,
  ],
  declarations: [
    Components.ViewInvoiceItemsComponent
  ],
  exports: [
    Components.ViewItemsComponent,
  ]
})
export class SharedModule {}

模块1.module.ts

    @NgModule({
      imports: [
        SharedModule,
      ],
      declarations: [
        HomeScreenComponent,
      ],
      providers: [
SharedService,
        [
          { provide: BASE_URL_TOKEN, useValue: 'module1/' }
        ]
      ]
    })
    export class Module1 {}

模块2.module.ts

    @NgModule({
      imports: [
        SharedModule,
      ],
      declarations: [
        HomeScreenComponent,
      ],
      providers: [
SharedService,
        [
          { provide: BASE_URL_TOKEN, useValue: 'module2/' }
        ]
      ]
    })
    export class Module2 {}

BASE_URL_TOKEN 值在 Shared 模块创建 SharedService 实例时设置。 SharedService 无法知道 BASE_URL_TOKEN 值的变化。 在您的情况下,要使其正常工作,您必须在每个模块上创建 SharedService 的新实例或明确告知 SharedService 您要使用的值。 另外,请阅读有关InjectionToken

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM