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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…