在我的angular 2应用程序中,我有一个父组件,我订阅了一个数据源,将这些数据传递给多个子组件。在我的一个子组件中,我尝试使用从顶部组件中进行的订阅接收的参数导航到我的应用程序中的不同路径。每当我在我的应用程序中执行此操作时,我都会收到此错误:
./CompanyPromoCardComponent类中的错误CompanyPromoCardComponent - 内联模板:6:10引起:无法读取属性'取消订阅'的 未定义
这是我的:CompanyPromoCardComponent
export class CompanyPromoCardComponent implements OnInit {
@Input() company:Object;
constructor(private router: Router) { }
ngOnInit() {
}
gotoDetail(_id: String) {
let link = ['/företag/' + _id + '/företagsinformation'];
this.router.navigate(link);
}
}
<div *ngIf="company">
<div class="panel panel-default">
<div class="panel-body">
<div class="row">
<div class="col-md-4">
<app-company-industry [company]='company' [sub]='sub'></app-company-industry>
</div>
<div class="col-md-8">
<app-company-targetgroup [company]='company'></app-company-targetgroup>
</div>
</div>
<app-company-description [company]='company'></app-company-description>
<app-company-tags [company]='company'></app-company-tags>
</div>
<div class="panel-footer">
<div>
<a class="btn btn-primary" (click)="gotoDetail(company._id)">Info</a>
</div>
</div>
</div>
</div>
这是我订阅我的数据的父组件:
export class SearchResultsComponent implements OnInit {
companies:Array<Object>;
user:Object;
sub:any;
constructor(
private companyService:CompanyService,
private authService:AuthService,
private flashMessage:FlashMessagesService
) { }
ngOnInit() {
this.sub = this.companyService.getCompaniesSearch().subscribe(data => {
console.log('data.companies: ' + data.companies);
this.companies = data.companies;
},
err => {
console.log(err);
return false;
});
}
ngOnDestroy(){
this.sub.unsubsribe();
}
}
company.industry组件 - 子组件
import { Component, OnInit, Input, OnDestroy } from '@angular/core';
@Component({
selector: 'app-company-industry',
templateUrl: './company-industry.component.html',
styleUrls: ['./company-industry.component.css']
})
export class CompanyIndustryComponent implements OnInit {
error: any;
@Input() sub: any;
navigated = false;
@Input() company:Object;
constructor(
) { }
ngOnInit() {
console.log(this.sub);
}
ngOnDestroy(){
this.sub.unsubscribe();
}
}
导致此错误的原因是什么?我很简单想要导航到另一条路线,该路线取决于从公司对象返回的id。
答案 0 :(得分:0)
在执行操作之前,检查变量是否未定义总是一个好习惯,
ngOnDestroy(){
if(this.sub){
this.sub.unsubscribe();
}
}
您的问题是多少,因为@input
变量是通过属性分配的。所以,你可以
this.companyService.getCompaniesSearch()
.skipWhile(data => {
return _.isEmpty(data);
})
.subscribe(data => {
console.log('data.companies: ' + data.companies);
this.companies = data.companies;
},
err => {
console.log(err);
return false;
}).unsubscribe();
注意: