gpt4 book ai didi

Angular 2 - 相当于路由器解析新路由器的数据

转载 作者:太空狗 更新时间:2023-10-29 17:12:46 26 4
gpt4 key购买 nike

我正在玩 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' }
])

因此,我遗漏了将数据从 Controller /组件传递到 @RouteConfig 的部分。

另一个问题——在 Angular 1.X 中,通过路由器的解析将数据传递到路由是一种很好的做法。使用 new router/components router 以这种方式将数据传递给组件是否仍然是一个好习惯?

编辑可以找到解决方案here - 使用 @CanActivate 事件

最佳答案

您必须将您的@RouteConfig 移动到 AppCmp 构造函数中:

//@RouteConfig([
// { path: '/', component: HomeCmp, as: 'Home', data: this.history },
// { path: '/about', component: AboutCmp, as: 'About' }
//])
export class AppCmp {
history: string[] = [];
constructor(public list: PersonalizationList,
private router_: Router) {
list.get('histoy', (response) => {
this.history = response;
});
router_.config([
{ path: '/', component: HomeCmp, as: 'Home', data: this.history },
{ path: '/about', component: AboutCmp, as: 'About' }
]);
}
}

在控制台输出我可以看到:

RouteData {data: "test sample"}

希望对您有所帮助!

关于Angular 2 - 相当于路由器解析新路由器的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34289761/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com