【发布时间】:2020-05-22 09:58:53
【问题描述】:
我试图在我的程序中实现路由。如果我在浏览器中输入 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 }
];
...
我的主组件调用一个带有按钮的函数。然而,该函数的一部分调用了子组件中的另一个函数。
MainComponent.html:
<button routerLink="/action" type="submit" (click)="function()" >Load</button>
..
..
<router-outlet></router-outlet>
MainComponent.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);
}
...
为什么它不能读取属性,我该怎么做才能修复它?
【问题讨论】:
-
您使用的是哪个版本的 Angular?请注意,所有最新版本的 Angular 都使用 ViewChild 的第二个参数。
-
@AngelaAmarapala 因为他没有收到关于她使用低于版本 8 的 viewchild 静态参数的错误
-
@AngelaAmarapala 我正在使用 7.3.8
标签: javascript angular angular2-routing typeerror