Open ChuangPoPO opened 7 years ago
2/15 : 新增heroes.component.ts及新的app.component.ts 修改app.moduel.ts 讓頁面還是可以正常運作, AppComponent僅負責作為導覽列(navigation), 真正在呈現資料則由HeroesComponent自己負責
next : Add Routing
<router-outlet></router-outlet>
?
The router displays each component immediately below the
2/20
可以執行,但畫面出不來,找不到問題,
在index.html內加入<base href="/">
就出現了
Next: Add a Dashboard
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<h1>{{title}}</h1>
<a routerLink="/heroes">Heroes</a>
<router-outlet></router-outlet>
`
})
export class AppComponent {
title = 'Tour of Heroes';
}
<router-outlet>
<a routerLink="/heroes">
RouterLinks
RouterModule 的 redirectTo 會將初始畫面引導到設定的位置,同時呈現在網址列。
2/22 加入了導覽列,可切換dashboard和heroes
Next time:Dashboard Top Heroes
templateUrl
property,指向新的template
@Component({
moduleId: module.id,
selector: 'my-dashboard',
templateUrl: './dashboard.component.html',
})
moduleId: module.id
使相對路徑的module載入 templateUrl
可參考1:http://stackoverflow.com/questions/37178192/angular2-what-is-the-meanings-of-module-id-in-component
可參考2:https://angular.io/docs/ts/latest/cookbook/component-relative-paths.html
使用 moduleId 在 @Component 內,則 templateUrl 則不在需要寫絕對路徑(absolute path),僅相對路徑(relative path)即可。
module.id 有啥用呢?我還不明白。
POPO:解答請見上方~~~
2/23
Next time:Share the HeroService
實作 DashboardComponent
export class DashboardComponent implements OnInit {
heroes: Hero[] = [];
constructor(private heroService: HeroService) { }
ngOnInit(): void {
this.heroService.getHeroes()
.then(heroes => this.heroes = heroes.slice(1, 5));
}
}
利用 Array.slice
method 讀取 4 位英雄
3/2
Next Step:Navigate to Hero Details
在 hero-detail.component.ts import
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';
import 'rxjs/add/operator/switchMap';
...
ngOnInit(): void {
this.route.params
.switchMap((params: Params) => this.heroService.getHero(+params['id']))
.subscribe(hero => this.hero = hero);
}
subscribe
(關注) method:用來偵測 id 的改變,(重新)設定檢索(retrieved) Hero3/27 Next step: Do you need to unsubscribe? 前的ngOnInit還看不懂
<!-- 呼叫 my-hero-detail component 用[hero]傳入selectedHero -->
<!-- hero-detail.component.ts 會用 @Input() 來接收這個selectedHero-->
<!-- 並assign給hero-detail.component.ts 內的 hero-->
<hero-detail [hero]="selectedHero"></hero-detail>
這段還是不知道怎麼運作的><
ngOnInit(): void{
this.route.params
.switchMap((params:Params) => this.heroService.getHero(+params['id']))
.subscribe(hero => this.hero = hero); //印出來看看(params)=>{console.log(params['id'])...
}
Add the Angular Router and learn to navigate among the views:
Action plan: