我正在使用 Angular 2.0 new router
,我尝试使用类似于 Angular 1.X ui-router / ng-route 解析机制的东西。
我试图通过以下方式实现这一目标RouteData
:
import {Component, ViewEncapsulation} from 'angular2/core';
import {
RouteConfig,
ROUTER_DIRECTIVES
} from 'angular2/router';
// import {HTTP_PROVIDERS} from 'angular2/http';
import {HomeCmp} from '../home/home';
import {AboutCmp} from '../about/about';
import {NameList} from '../../services/name_list';
import {PersonalizationList} from '../../services/personalization_list';
@Component({
selector: 'app',
viewProviders: [NameList, PersonalizationList],
templateUrl: './components/app/app.html',
styleUrls: ['./components/app/app.css'],
encapsulation: ViewEncapsulation.None,
directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
{ path: '/', component: HomeCmp, as: 'Home', data: this.history },
{ path: '/about', component: AboutCmp, as: 'About' }
])
export class AppCmp {
history: string[] = [];
constructor(public list: PersonalizationList) {
list.get('histoy', (response) => {
this.history = response;
});
}
}
使用这个 ( home
) 的组件:
import {Component} from 'angular2/core';
import {PersonalizationList} from '../../services/personalization_list';
import {Router, ROUTER_DIRECTIVES, routerBindings, RouteConfig, RouteData} from 'angular2/router';
@Component({
selector: 'home',
templateUrl: './components/home/home.html',
styleUrls: ['./components/home/home.css'],
directives: [ROUTER_DIRECTIVES]
})
export class HomeCmp {
constructor(data: RouteData) {
console.log(data);
}
}
记录到控制台的数据不是我从服务初始化的数据。如果我直接在 中初始化它@RouteConfig
,它将起作用。例如:
@RouteConfig([
{ path: '/', component: HomeCmp, as: 'Home', data: [1,2,3,4] },
{ path: '/about', component: AboutCmp, as: 'About' }
])
所以,我错过了将数据从控制器/组件传递到@RouteConfig
.
另一个问题 - 在 Angular 1.X 中,通过路由器的解析将数据传递给路由是一种很好的做法。new router
使用/以这种方式将数据传递给组件仍然是一种好习惯components router
吗?
编辑
可以在这里找到解决方案- 使用@CanActivate
事件