Javascript 角度路由器:无法读取属性'';未定义的

Javascript 角度路由器:无法读取属性'';未定义的,javascript,angular,angular2-routing,typeerror,Javascript,Angular,Angular2 Routing,Typeerror,我试图在我的程序中实现路由。如果我在浏览器中键入URL,则基本路由有效。但是,如果我想从主组件使用我的按钮,我会得到一个错误:无法读取未定义的属性'loadFromJson'。 在我实现路由器之前,它就像现在一样工作正常 My app-routing.module: ... const appRoutes: Routes = [ { path: 'start', component: FrontPageComponent }, { path: 'action', co

我试图在我的程序中实现路由。如果我在浏览器中键入URL,则基本路由有效。但是,如果我想从主组件使用我的按钮,我会得到一个错误:无法读取未定义的属性'loadFromJson'。

在我实现路由器之前,它就像现在一样工作正常

My 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>

为什么它不能读取属性,我可以做些什么来修复它?

要在方法中引用类变量,请使用
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),
    );
}
@ViewChild(ChildComponent)ChildComponent;
...
函数():void{
this.DownloadService.downloadsource(this.url).subscribe(
json=>this.childComponent.loadFromJson(json,this.url),//this.setError(err),
);
}

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

@ViewChild(ChildComponent)ChildComponent;
downloadResource():void{
this.DownloadService.downloadsource(this.url).subscribe(
json=>this.childComponent.loadFromJson(json,this.url),
err=>this.setError(err),
);
}
ngAfterViewInit():void{
此文件为.downloadResource();
}

查看更多详细信息

您使用的是哪个版本的angular?请注意,angular的所有最新版本都为ViewChild使用了第二个参数。@AngelaAmarapala因为他没有得到关于ViewChild静态参数的错误,所以她使用的是小于版本8@AngelaAmarapala我使用的是7.3.8在这种情况下,请查看答案当我使用Inf ViewCildren时,它说:。loadFromJson不是function@pattplatt我有最新消息例如,答案是否解决了您的问题?不幸的是,没有,我尝试使用ngAfterViewInit():void{this.resourceDownloadService.downloadResource()}仍然是相同的错误。但是,如果使用@ViewChildren,我会得到错误:。loadFromJson不是函数
 private loadFromJson(json: any, id: string): void {
   this.initEmptyContainer();
   this.addFromJson(json, id);
}
 ...
@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),
    );
}