我正在尝试使用 ActivatedRoute 在angular2中导航时读取传递的参数,但是当我尝试this.route.params
时,我将this.route
作为 undefined 。这是我的描述组件的代码
import {Component, OnInit} from "angular2/core";
import {ActivatedRoute} from "angular2/router";
import {LocalStorageService} from "app/common/services/data/localStorageService";
@Component({
selector: "description",
template: `
{{ data.name }}
`,
providers: [LocalStorageService]
})
export class Description implements OnInit {
data: Object;
constructor(private service: LocalStorageService, private route: ActivatedRoute) {}
ngOnInit() {
this.route.params.forEach((params: Params) => {
this.data = this.service.getInformation(params["name"]);
});
}
}
我已使用RouteConfig
@RouteConfig([{
path: "",
component: Dashboard,
name: "Dashboard"
}, {
path: "/:name",
component: Description,
name: "Description"
}])
我正在使用以下代码进行导航
onCardClick(item) {
this.router.navigate(["Description", {
name: item.name
}]);
}
我尝试在提供商中添加 ActivatedRoute ,但似乎没有帮助。在代码执行时,我收到此错误
EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in :0:0
ORIGINAL EXCEPTION: TypeError: Cannot read property 'params' of undefined
ORIGINAL STACKTRACE:
TypeError: Cannot read property 'params' of undefined
at new Description
(http://localhost:3000/app/pages/description/components/Description.js:27:43)
at AppView._View_Description_Host0.createInternal (Description_Host.template.js:15:32)
at AppView.create (http://localhost:3000/lib/angular2.dev.js:23468:23)
at ComponentFactory.create (http://localhost:3000/lib/angular2.dev.js:7673:34)
at ViewContainerRef_.createComponent (http://localhost:3000/lib/angular2.dev.js:5763:43)
at http://localhost:3000/lib/angular2.dev.js:4147:25
at ZoneDelegate.invoke (http://localhost:3000/lib/angular2-polyfills.js:349:29)
at Object.onInvoke (http://localhost:3000/lib/angular2.dev.js:2189:31)
at ZoneDelegate.invoke (http://localhost:3000/lib/angular2-polyfills.js:348:35)
at Zone.run (http://localhost:3000/lib/angular2-polyfills.js:242:44)
ERROR CONTEXT:
[object Object]
答案 0 :(得分:1)
您似乎是angular2的旧版本。以下在Angular 2.1.0的上下文中有效
ngOnInit() {
let name = this.route.snapshot.params["name"];
}
答案 1 :(得分:0)
导入句子'angular2 / core'应为'@ angular / core'。