angular2 routing - How to reuse a Single Component with multiple routes without creating instance of Component again -


i having 2 routes first list , second details each single item in list. displaying few values each element in list action link , when link clicked passes id method viewcoupon() , route changes resulting in error. how should avoid creating instance again , call different route. code looks 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();  /**   * first time empty , second time when has value     console error saying 'cannot read property 'find' of undefined'     here assume component instance 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 null here.     console.log(this.coupons);    }    //when click triggered below called     viewcoupon(id: number) {      this.displaytype = "view";      this._router.navigate(['admin/coupons/view', id]);        }  } 

the routes looks below:

      {path: 'coupons', component: couponscomponent},       {path:'coupons/view/:id',component:couponscomponent}, 

how should change route , avoid calling service in next call.

please check getcoupon() method. might b returning undefined.

getcoupon() {  this.couponsservice.getcoupons().subscribe(data => { this.couponlist = data; }, error => { console.log(error) }); 

}

so, when pass route parameter it, getcoupondetails() method gets called , compliler finds couponlist undefined , therefor unable call find method on undefined object


Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -