Friday, 7 May 2021

Angular dependency Injection(Inject service to component level only)

https://stackoverflow.com/questions/54297993/angular-component-level-service-inject-another-component-level-service

https://angular.io/guide/dependency-injection-providers

 @Component({

  selector: 'my-component',
  templateUrl: './my-component.html',
  providers: [ServiceA, ServiceB]
})
export class component {
constructor (
private serviceA: ServiceA
) {}
}

---------------------------------------------------

@Injectable()
export class ServiceA {
  constructor(private serviceB: ServiceB){}

  someMethod() {
     this.serviceB.makeSomething(); 
  }
}

--------------------------------This way service will only belong to current component



By default Service belong to root component, so its 1 instance for every component as shown below




@Injectable({

    providedIn: 'root',

})

export class ServiceC {



No comments:

Post a Comment