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

3
  • 1
    You can read more about here:angular.io/guide/providers Commented Apr 4, 2023 at 16:44
  • In the second component you haven't any providers. Commented Apr 4, 2023 at 18:11
  • @Chellappanவ Thanks, m8. Really helped me out to get the problem. It seems like Angular makes one injector instance that is used on every non-lazy module. Commented Apr 4, 2023 at 18:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.