Skip to content

Instantly share code, notes, and snippets.

@Bhavdip
Last active September 25, 2017 10:16
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 Bhavdip/e40f59027501547c9dc2bb22f570ec49 to your computer and use it in GitHub Desktop.
Save Bhavdip/e40f59027501547c9dc2bb22f570ec49 to your computer and use it in GitHub Desktop.
AngularTopics Series 3

** Services and Dependency Injection **

import { Component, EventEmitter, Input, Output } from '@angular/core';
import {LoggingService} from "../logging.service";

@Component({
  selector: 'app-account',
  templateUrl: './account.component.html',
  styleUrls: ['./account.component.css'],
  providers:[LoggingService] //<-- service injection
})
export class AccountComponent {
  @Input() account: {name: string, status: string};
  @Input() id: number;
  @Output() statusChanged = new EventEmitter<{id: number, newStatus: string}>();


  constructor(private loggingService: LoggingService){ //<-- service injection

  }

  onSetTo(status: string) {
    this.statusChanged.emit({id: this.id, newStatus: status});
    //console.log('A server status changed, new status: ' + status);
    this.loggingService.logStatusChange(status);
  }
}

** Hierachical Injector ** It's similar like Dagger2 scope of instance

AppModule : Same Instance of Service is available Application-wide. AppComponent: Same Instance Of Service is available for allComponants(but not for other services) Any Other Component: Same Instance Of Service is available for the Component and all its child components.

@Injectable(): If you want to inject the one service into another service.

@Injectable()
export class AccountsService {
  accounts = [
    {
      name: 'Master Account',
      status: 'active'
    },
    {
      name: 'Testaccount',
      status: 'inactive'
    },
    {
      name: 'Hidden Account',
      status: 'unknown'
    }
  ];

  constructor(private loggingService:LoggingService){
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment