【问题标题】:Angular Router: Cannot read property ' ' of undefinedAngular 路由器:无法读取未定义的属性“”
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 在这种情况下,请查看this answer
  • 当我使用 ViewCildren 时,它会说:.loadFromJson 不是函数
【解决方案2】:

视图查询是在调用 ngAfterViewInit 回调之前设置的。

@ViewChild(ChildComponent) childComponent;

 downloadResource (): void { 
  this.DownloadService.downloadResource(this.url).subscribe(
     json => this.childComponent.loadFromJson(json, this.url),
          err => this.setError(err),
        );
      }

 ngAfterViewInit(): void {
    this.downloadResource();
  }

查看here了解更多详情

【讨论】:

  • @pattplatt 我已经更新了类似的东西,答案解决了你的问题吗?
  • 很遗憾没有,我用 ngAfterViewInit() 试过了:void { this.resourceDownloadService.downloadResource() } 还是一样的错误
  • 但是,如果我使用 @ViewChildren 我得到错误:.loadFromJson 不是函数
猜你喜欢
  • 2016-12-28
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 2018-10-17
  • 2020-10-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多