** 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){
}