首页 > 解决方案 > 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);
}
 ...

为什么它不能读取属性,我该怎么做才能修复它?

标签: javascriptangularangular2-routingtypeerror

解决方案


要在方法中引用类变量,请使用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),
    );
}

推荐阅读