Benutzer:MovGP0/Angular/Dependency Injection

aus Wikipedia, der freien Enzyklopädie
Zur Navigation springen Zur Suche springen
   MovGP0        Über mich        Hilfen        Artikel        Weblinks        Literatur        Zitate        Notizen        Programmierung        MSCert        Physik      

Dependency Injection

[Bearbeiten | Quelltext bearbeiten]
mock-heroes.ts
import { Hero } from './hero';
export const HEROES: Hero[] = [
  {id: 11, name: 'Mr. Nice'},
  {id: 12, name: 'Narco'},
  {id: 13, name: 'Bombasto'},
  {id: 14, name: 'Celeritas'},
  {id: 15, name: 'Magneta'},
  {id: 16, name: 'RubberMan'},
  {id: 17, name: 'Dynama'},
  {id: 18, name: 'Dr IQ'},
  {id: 19, name: 'Magma'},
  {id: 20, name: 'Tornado'}
];
hero.service.ts
import { Injectable } from '@angular/core';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';

@Injectable()
export class HeroService {
    getHeroes(): Hero[] {
      return HEROES;
    }

    getHeroesAsync(): Promise<Hero[]> {
        return Promise.resolve(HEROES);
    }
}
app.component.ts
import { Component } from '@angular/core';
import { Hero } from './hero';
import { HeroService } from './hero.service';

@Component(
    selector: 'my-app',
    providers: [HeroService], 
    templateUrl: 'app.html'
)
export class App 
{
    heroes: Hero[];
    
    constructor(private heroService: HeroService) {
        this.heroes = this.heroService.getHeroes();
        this.heroService.getHeroesAsync().then(heroes => this.heroes = heroes);
        // Typescript 2.1+
        this.heroes = await this.heroService.getHeroesAsync();
    }
}

|}