gpt4 book ai didi

javascript - ActivatedRoute 在 angular2 中设置为未定义

转载 作者:搜寻专家 更新时间:2023-10-30 21:52:37 24 4
gpt4 key购买 nike

我正在尝试使用 ActivatedRoute 在 angular2 中导航时读取传递的参数,但是当我尝试 this.route.params 时,我得到了 this.route未定义。这是我的描述组件代码

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]

最佳答案

你似乎是angular2的旧版本。以下在 Angular 2.1.0 的上下文中工作。

ngOnInit() {
let name = this.route.snapshot.params["name"];
}

关于javascript - ActivatedRoute 在 angular2 中设置为未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40451319/

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