|
1 | 1 | import { Component } from '@angular/core'; |
2 | | - |
3 | | - |
4 | | -export class Hero { |
5 | | - id: number; |
6 | | - name: string; |
7 | | -} |
8 | | - |
9 | | -const HEROES: Hero[] = [ |
10 | | - { id: 11, name: 'Mr. Nice' }, |
11 | | - { id: 12, name: 'Narco' }, |
12 | | - { id: 13, name: 'Bombasto' }, |
13 | | - { id: 14, name: 'Celeritas' }, |
14 | | - { id: 15, name: 'Magneta' }, |
15 | | - { id: 16, name: 'RubberMan' }, |
16 | | - { id: 17, name: 'Dynama' }, |
17 | | - { id: 18, name: 'Dr IQ' }, |
18 | | - { id: 19, name: 'Magma' }, |
19 | | - { id: 20, name: 'Tornado' } |
20 | | -]; |
21 | | - |
22 | | - |
| 2 | +import { Hero } from './hero'; |
| 3 | +import { HeroService } from './hero.service'; |
| 4 | +import { OnInit } from '@angular/core'; |
23 | 5 |
|
24 | 6 | @Component({ |
25 | 7 | selector: 'app-root', |
26 | 8 | template: ` |
27 | 9 | <h1>{{title}}</h1> |
28 | 10 | <ul class="heroes"> |
29 | | - <li *ngFor="let hero of heroes" (click)="onSelect(hero)" [class.selected]="hero === selectedHero"> |
| 11 | + <li *ngFor="let hero of heroes" |
| 12 | + (click)="onSelect(hero)" |
| 13 | + [class.selected]="hero === selectedHero"> |
30 | 14 | <span class="badge">{{hero.id}}</span> {{hero.name}} |
31 | 15 | </li> |
32 | 16 | </ul> |
33 | | - <div *ngIf="selectedHero"> |
34 | | - <h2>{{selectedHero.name}} details!</h2> |
35 | | - <div><label>id: </label>{{selectedHero.id}}</div> |
36 | | - <div> |
37 | | - <label>name: </label> |
38 | | - <input [(ngModel)]="selectedHero.name" placeholder="name"/> |
39 | | - </div> |
40 | | - </div> |
| 17 | + <hero-detail [hero]="selectedHero"></hero-detail> |
41 | 18 | `, |
42 | | - styleUrls: ['./app.component.css'] |
| 19 | + styleUrls: ['./app.component.css'], |
| 20 | + providers: [HeroService] |
43 | 21 | }) |
44 | 22 |
|
45 | | -export class AppComponent { |
| 23 | + |
| 24 | +export class AppComponent implements OnInit { |
46 | 25 | title = 'Tour of Heroes'; |
47 | | - heroes = HEROES; |
| 26 | + heroes: Hero[]; |
48 | 27 | selectedHero: Hero; |
49 | 28 |
|
| 29 | + constructor(private heroService: HeroService) { } |
| 30 | + |
50 | 31 | onSelect(hero: Hero): void { |
51 | 32 | this.selectedHero = hero; |
52 | 33 | } |
| 34 | + |
| 35 | + ngOnInit(): void { |
| 36 | + this.getHeroes(); |
| 37 | + } |
| 38 | + |
| 39 | + getHeroes(): void { |
| 40 | + this.heroService.getHeroes().then(heroes => this.heroes = heroes); |
| 41 | + // this.heroService.getHeroesSlowly().then(heroes => this.heroes = heroes); |
| 42 | + } |
53 | 43 | } |
0 commit comments