interview community logo

1
0
What happens if a service provided in component use a service provided in root
1 answer

now you have two services like that

@Injectable({
  providedIn: 'root'
})
export class ProvidedInRootService {
  constructor() {
    console.log('ProvidedInRootService.constructor');
  }

  get foo() {
    return 'foo';
  }
}

@Injectable()
export class ProvidedInComponentService {
  private readonly providedInRootService = inject(ProvidedInRootService);

  constructor() {
    console.log('ProvidedInComponentService.constructor');
  }

  get foo() {
    return this.providedInRootService.foo;
  }
}

and a component consuming the second one like that

@Component({
  selector: 'app-foo',
  standalone: true,
  template: '',
  providers: [ProvidedInComponentService]
})
export class FooComponent {
  private readonly providedInComponentService = inject(ProvidedInComponentService);

  constructor() {
    console.log(this.providedInComponentService.foo);
  }
}

and this component is used like that

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, FooComponent],
  template: '<app-foo *ngFor="let item of array"></app-foo>',
})
export class AppComponent {
  array = [1, 2, 3];
}

how many times will ProvidedInRootService.constructor and ProvidedInComponentService.constructor be printed?

can you explain why this output is like that?

Angular Robert Isaac asked 1 year ago


0

the output will be

ProvidedInRootService.constructor
ProvidedInComponentService.constructor
foo
ProvidedInComponentService.constructor
foo
ProvidedInComponentService.constructor
foo

now because FooComponent is in an NgFor loop with array of 3 items, it will be instantiated 3 times, with each time it will print one foo

and because ProvidedInComponentService service is provided in the component, each time the component is instantiated, a new instance of the service is instantiated for it and because it's a dependency for the component, it gets instantiated first, that's why before each foo there is ProvidedInComponentService.constructor

and since ProvidedInRootService service is provided in root, it will be only instantiated once, it's instantiated before ProvidedInComponentService because it's its dependency

Robert Isaac answered 1 year ago loading comments...