Yara Ameen
Yara Ameen

Reputation: 21

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.

Scenario: Firstly I navigate to module1, the response is returned correctly with module1 items, then I navigate to modules, the HTTP request is sent by module1 URL so it is returned wrong items

shared.service.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 {}

module1.module.ts

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

module2.module.ts

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

Upvotes: 2

Views: 346

Answers (1)

rood
rood

Reputation: 12853

BASE_URL_TOKEN value is set when Shared module create instance of SharedService. SharedService can't know about changes of BASE_URL_TOKEN value. In your case, to make it work you would have to create new instance of SharedService on each module or inform SharedService, explicitly about value you want to use. Also, please read about InjectionToken

Upvotes: 1

Related Questions