问题
I am having two routes the first will get the list and the second get the details for each single item in a list. Initially I am displaying few values for each element in list with an action link and when the link is clicked it passes an id to method viewCoupon() and the route changes resulting in an error. How should I avoid creating an instance again and just call a different route. The code looks like below.
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]);
}
}
The routes looks like below:
{path: 'coupons', component: CouponsComponent},
{path:'coupons/view/:id',component:CouponsComponent},
How should I change the route and avoid calling the service in the next call.
回答1:
please check you getCoupon() method. It might b returning undefined.
getCoupon() {
this.couponsService.getCoupons().subscribe(data => { this.couponList = data; }, error => { console.log(error) });
}
so, when you pass the route parameter to it, your getCouponDetails() method gets called and the compliler finds the couponList as undefined and therefor is unable to call the find method on undefined object
回答2:
Please us the below code to declare and initialize couponList object
Use this: public couponList: Array<Coupons> = [];
Instead of this : public couponList: Array<Coupons>;
来源:https://stackoverflow.com/questions/45790858/how-to-reuse-a-single-component-with-multiple-routes-without-creating-instance-o