我有两条路线,第一条将获取列表,第二条将获取列表中每个项目的详细信息。最初,我使用操作链接为列表中的每个元素显示几个值,当单击链接时,它会将 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},
我应该如何更改路由并避免在下一次调用中调用服务。
请检查您的getCoupon((方法。它可能会返回未定义。
getCoupon() {
this.couponsService.getCoupons().subscribe(data => { this.couponList = data; }, error => { console.log(error) });
}
因此,当您将 route 参数传递给它时,您的 getCouponDetails(( 方法会被调用,编译器会发现 couponList 未定义,因此无法在未定义的对象上调用 find 方法
请用下面的代码来声明和初始化优惠券列表对象
使用这个:public couponList: Array<Coupons> = [];
取而代之的是:public couponList: Array<Coupons>;