javascript - Angular 路由器:无法读取未定义的属性“”
问题描述
我试图在我的程序中实现路由。如果我在浏览器中输入 URL,则基本路由将起作用。但是,如果我想使用 MainComponent 中的按钮,则会出现错误:无法读取未定义的属性“loadFromJson”。
在我实现路由器之前,它就像现在一样工作得很好。
我的 app-routing.module:
...
const appRoutes: Routes = [
{ path: 'start', component: FrontPageComponent },
{ path: 'action', component: MainComponent },
{ path: '', redirectTo: '/start', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent }
];
...
我的 Main 组件调用一个带有按钮的函数。然而,该函数的一部分调用了子组件中的另一个函数。
主要组件.html:
<button routerLink="/action" type="submit" (click)="function()" >Load</button>
..
..
<router-outlet></router-outlet>
主要组件.ts
@ViewChild(ChildComponent) childComponent; <--imported ChildComponent with @ViewChild
...
function(): void {
this.DownloadService.downloadResource(this.url).subscribe(
json => this.childComponent.loadFromJson(json, this.url), <--function from childComponent
err => this.setError(err),
);
}
子组件中的功能:
childComponent.ts:
private loadFromJson(json: any, id: string): void {
this.initEmptyContainer();
this.addFromJson(json, id);
}
...
为什么它不能读取属性,我该怎么做才能修复它?
解决方案
要在方法中引用类变量,请使用this.childComponent
尝试这个
@ViewChild(ChildComponent) childComponent;
...
function(): void {
this.DownloadService.downloadResource(this.url).subscribe(
json => this.childComponent.loadFromJson(json, this.url), // <-- Refer your childComponent using this
err => this.setError(err),
);
}
推荐阅读
- json - Postman 是否支持控制请求体的格式?
- data-warehouse - informatica 代码在 Dev 中生成了 476 Gigs 的会话日志
- amazon-web-services - 在数据管道 ec2 实例上运行 docker
- spring - Spring Kafka - 如何使用 @KafkaListener 重试
- django - 在 django 模板中对 div 进行排序
- sql-server - 是否有一些快速的方法可以将 ADO 记录集转储到新的 MS ACCESS 表中?
- python-3.x - **kwargs 在 mpi4py MPIPoolExecutor 中不起作用
- html - UI 字段未水平居中对齐
- android - 找不到片段构造函数
- sql - 带有 in group by 或 partition by 子句的 case 语句