Skip to content

Instantly share code, notes, and snippets.

@Yojih
Last active July 26, 2018 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yojih/199b135d0653066ae28efc1fb3b5c53b to your computer and use it in GitHub Desktop.
Save Yojih/199b135d0653066ae28efc1fb3b5c53b to your computer and use it in GitHub Desktop.
[Angular services & dependency injection] #angular

Links

https://angular.io/guide/dependency-injection#injectable-ngmodule-or-component

Create service

  $ng generate service heroes/hero


  import { Injectable } from '@angular/core';

  @Injectable({
    // we declare that this service should be created
    // by the root application injector.
    providedIn: 'root',
  })

  @Injectable({
    // we declare that this service should be created
    // by any injector that includes HeroModule.
    providedIn: HeroModule,
  })

Component level and child

  @Component({
  selector: 'app-unsorted-heroes',
  template: `<div *ngFor="let hero of heroes">{{hero.name}}</div>`,
  providers: [HeroService]
})
export class HeroesBaseComponent implements OnInit {
  constructor(private heroService: HeroService) { }
}

Sets or overrides the provider for MyService to the MyMockService class.

{ provide: MyService, useClass: MyMockService } 	

Sets or overrides the provider for MyService to the myFactory factory function.

{ provide: MyService, useFactory: myFactory } 	

Sets or overrides the provider for MyValue to the value 41.

{ provide: MyValue, useValue: 41 } 	
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment