0

so i have started to learn more about Dependency Injection. And as it was written in Docs, i expect that if i have 2 separate modules and both of them have their own provider in provider array. I'll get different singletone instances for both of the modules. However, i am getting the same one.

Here are my modules

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FirstModule,
    SecondModule
  ],
  providers: [FirstService],
  bootstrap: [AppComponent]
})
export class AppModule { }


@NgModule({
  declarations: [
    FirstComponent
  ],
  imports: [
    CommonModule
  ],
  exports: [FirstComponent],
  providers: [FirstService]
})
export class FirstModule { }



@NgModule({
  declarations: [SecondComponent],
  imports: [
    CommonModule
  ],
  exports: [SecondComponent]
})
export class SecondModule { }

And here are my components code

@Component({
  selector: 'app-first',
  templateUrl: './first.component.html',
  styleUrls: ['./first.component.scss']
})
export class FirstComponent implements OnInit{
  constructor(private firstService: FirstService) {}

  ngOnInit(): void {
    console.log("FirstService in FirstComponent", this.firstService.randomNumberAsStr);
  }
}

@Component({
  selector: 'app-second',
  templateUrl: './second.component.html',
  styleUrls: ['./second.component.scss']
})
export class SecondComponent implements OnInit{
  constructor(private firstService: FirstService) {}

  ngOnInit(): void {
    console.log("FirstService in SecondComponent", this.firstService.randomNumberAsStr);
  }
}

FirstService generates random number

@Injectable()
export class FirstService {

  public randomNumberAsStr: string;
  constructor() {
    this.randomNumberAsStr = (Math.random() * 100).toFixed();
  }
}

Thats what i get in console enter image description here

Iceneo
  • 51
  • 3

0 Answers0