How to reuse a single component with multiple routes without re-creating the component instance

I have two routes: the first will receive the list, and the second will receive the details for each individual item in the list. Initially, I show several values ​​for each item in the list with a link to the action, and when I click on the link, it passes the identifier to the viewCoupon () method, and route changes result in an error. Avoiding re-creating the instance and just calling another route. The code is as follows.

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]);    
   }
 }

Routes are as follows:

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

How can I change the route and avoid calling the service on the next call.

-1
source share
2 answers

, getCoupon(). undefined.

getCoupon() {
 this.couponsService.getCoupons().subscribe(data => { this.couponList = data; }, error => { console.log(error) });

}

, , getCouponDetails(), couponList undefined find undefined object

0

, couponList

: public couponList: Array<Coupons> = [];

: public couponList: Array<Coupons>;

0

Source: https://habr.com/ru/post/1664518/


All Articles