Angular2笔记6-router

之前感觉Angular2这玩意越看越像jsp, 又是一大堆根本记不住的语法
现在看来是把后端MVC那一套也搞到前端来了… 估计又是一堆依赖注入的配置

1.设置 base 标签

推荐加一级后缀名, 比如.component.ts和 .service.ts

1
2
<head>
<base href="/">

## 2.main.js里加载router

1
2
3
4
5
6
7
8
import { bootstrap } from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component';
import { appRouterProviders } from './app.routes';
bootstrap(AppComponent, [
appRouterProviders
]);

3.app.routes.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { provideRouter, RouterConfig } from '@angular/router';
import { DashboardComponent } from './dashboard.component';
import { HeroesComponent } from './heroes.component';
import { HeroDetailComponent } from './hero-detail.component';
const routes: RouterConfig = [
{
path: '',
redirectTo: '/dashboard',
pathMatch: 'full'
},
{
path: 'dashboard',
component: DashboardComponent
},
{
path: 'detail/:id',//RestFul风格的占位符
component: HeroDetailComponent
},
{
path: 'heroes',//浏览器地址
component: HeroesComponent//切换到此路由时,需要创建的组件
}
];
export const appRouterProviders = [
provideRouter(routes)
];

app.component.ts

Router的内容会被渲染到

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Component({
template: `
<nav>
<a [routerLink]="['/dashboard']" routerLinkActive="active">Dashboard</a>
<a [routerLink]="['/heroes']" routerLinkActive="active">Heroes</a>
</nav>
<router-outlet></router-outlet>
`,
directives: [ROUTER_DIRECTIVES],
})
...
```
返回就是url操作
``` js
goBack() {
window.history.back();
}

以path: ‘detail/:id’为例

1
2
3
4
{
path: 'detail/:id',//RestFul风格的占位符
component: HeroDetailComponent
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
export class HeroDetailComponent implements OnInit, OnDestroy {
hero: Hero;
sub: any;
constructor(
private heroService: HeroService,
private route: ActivatedRoute) {
}
ngOnInit() {
//订阅this.route.params的参数变化事件
this.sub = this.route.params.subscribe(params => {
let id = +params['id'];//url里的id, 强转为数字
this.heroService.getHero(id).then(hero => this.hero = hero);
});
}
ngOnDestroy() {
//销毁时候, 解除时间绑定
this.sub.unsubscribe();
}
goBack() {
//url返回
window.history.back();
}
}

管道

1
{{selectedHero.name | uppercase}} is my hero