Components and Services

ng-metadata lets us write code in an Angular style. Components writtenin this style are prime candidates for an eventual upgrade using ng-upgrade.

Components

Components use @Component from ng-metadata. Lifecycle hooks similar to thosein Angular should work with ng-metadata.

  1. import { Component, Inject, Input, Output, EventEmitter, OnInit } from 'ng-metadata/core';
  2. import { HeroService } from './hero.service';
  3. @Component({
  4. selector: 'hero',
  5. templateUrl: './hero.component.html'
  6. })
  7. export class HeroComponent implements OnInit {
  8. @Input() name: string;
  9. @Output() call = new EventEmitter<void>();
  10. // Services can be included using `@Inject` or by their class literal
  11. constructor(
  12. @Inject('$log') private $log: ng.ILogService,
  13. private heroSvc: HeroService
  14. ){
  15. }
  16. ngOnInit() {
  17. console.log('Component initialized');
  18. }
  19. }

Services

Services use @Injectable from ng-metadata. This decorator is written precedinga TypeScript class. Angular 1 services can be added by using the @Injectdecorator in the service constructor.

  1. import { Injectable, Inject } from 'ng-metadata/core';
  2. @Injectable()
  3. export class HeroService {
  4. constructor(@Inject('$http') private $http: ng.IHttpService){
  5. }
  6. fetchAll(){
  7. return this.$http.get('/api/heroes');
  8. }
  9. }

原文: https://angular-2-training-book.rangle.io/handout/migrate/ng-metadata/components-and-services.html