1
votes

I'm using Angular Core/Feature/Shared modules pattern.

When CoreComponent (the app's home page) is rendered, the DataStorageService's constructor (which is used in CoreComponent's constructor) is called multiple times (which results in a AJAX call each time the constructor is called)

Please don't mark my question as duplicate, as my question is a bit different than similar questions which have been asked and answered here before.
I attached my code to show what I mean ( I have shortened it for simplicity).

core/shared.module.ts

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

  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [XHRService, DataStorageService]
    };
  }
}

shared/services/data-storage.service.ts

@Injectable()
export class DataStorageService {
  constructor(private xhr: XHRService) {
    this.loadEvents()
  }

  public loadOrigination = () => this.xhr.getOriginationsList().subscribe(this.originationsSource);
  public loadEvents = () => this.xhr.getEventsList().subscribe(this.eventsSource);

  private eventsSource = new BehaviorSubject(null);
  private originationsSource = new BehaviorSubject(null);

  public originations$ = this.originationsSource.asObservable();
  public events$ = this.eventsSource.asObservable();
}

app.module.ts

@NgModule({
  declarations: [...],
  imports: [
    SharedModule.forRoot(),
   ...
  ],
  providers: [...],
  bootstrap: [AppComponent]
})
export class AppModule { }

core/core.module.ts

@NgModule({
  declarations:
    [
      CoreComponent,
      ...
    ],
  exports: [
    CoreComponent
  ],
  imports: [
    CoreRoutingModule,
    SharedModule
    ...
  ],
})
export class CoreModule { }

core/core.component.ts

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements{

  constructor(public dataStorageService : DataStorageService) { }

}
1
Making calls from inside of constructors is a bad idea in any context. Can you move the code out? - theMayer
Where should I move them to? - Rafi Henig
Put it somewhere where it makes sense, not in the constructor. - theMayer

1 Answers

1
votes

This is as expected, The Constructor is a default method of the class that is executed when the class is instantiated and ensures all the fields of the class are properly initialized. The constructor of the component is called when Angular constructs components tree. All lifecycle hooks are called as part of running change detection. So whenever you are injecting core components to any module it is going to get called.

The suggestion to fix this issue would be, remove your loadEvents() outside the constructor/ call it in the component with ngOnInit life cycle hook.

 ngOnInit(){
   this.dataStorageService.loadEvents();
 }