我有两个路线,第一个将获得列表,第二个路径获取列表中每个项目的详细信息。最初我使用动作链接为列表中的每个元素显示几个值,并且当单击链接时,它将id传递给方法viewCoupon(),并且路径更改导致错误。 我应该如何避免再次创建实例并只调用不同的路由。 代码如下所示。
export class CouponsComponent implements OnInit{
public couponList: Array<Coupons>;
coupons = new Coupons;
displayType?: string;
constructor(private couponsService: CouponsService,
private _fb: FormBuilder,
public errorhandler: ErrorHandlerService,
public _router: Router,
public _route: ActivatedRoute
) { }
ngOnInit() {
this.getCoupon();
/**
* The first time this is empty and the second time when this has value
I get an console error saying 'Cannot read property 'find' of undefined'
Here I assume the Component instance is getting created again.
*/
this._route.params.subscribe((params: any) => {
if (params['id']) {
this.getCouponDetails(params['id']);
}
})
}
createCoupon(coupons) {
this.couponsService.createCoupon(coupons).subscribe(data => {
this.getCoupon()},
error => {
let ErrorDetails = this.errorhandler.setError(error);
this.errorMsg = ErrorDetails.ErrorMsg;
});
}
getCoupon() {
this.couponsService.getCoupons().subscribe(data => { this.couponList = data; }, error => { console.log(error) });
}
getCouponDetails(id: number) {
this.coupons = this.couponList.find(c => c.id == id);//couponList is null here.
console.log(this.coupons);
}
//When a click is triggered the below is called
viewCoupon(id: number) {
this.displayType = "view";
this._router.navigate(['admin/coupons/view', id]);
}
}
路线如下所示:
{path: 'coupons', component: CouponsComponent},
{path:'coupons/view/:id',component:CouponsComponent},
我应该如何更改路线并避免在下一次通话中拨打该服务。
答案 0 :(得分:0)
请检查你的getCoupon()方法。它可能会返回undefined。
getCoupon() {
this.couponsService.getCoupons().subscribe(data => { this.couponList = data; }, error => { console.log(error) });
}
所以,当你将route参数传递给它时,你的getCouponDetails()方法被调用,并且compliler发现couponList为undefined,因此无法在未定义的对象上调用find方法
答案 1 :(得分:0)
请输入以下代码来声明和初始化couponList对象
使用此:public couponList: Array<Coupons> = [];
而不是:public couponList: Array<Coupons>;