2

I am working on sample Angular 2 application , and below is the code of one of my components.

export class ProductComponent implements OnInit {

  product:Product;

  constructor(private appService: AppService , private router:Router ,private route:ActivatedRoute) {}

 ngOnInit() 
 {

    let id:string;
    let pid:string;

    this.route.params.subscribe( (params) => {
    id = params['id'];
    pid = params['pid'];       
    this.appService.GetProduct(id,pid).subscribe( data => {
        this.product = data;
    });
})

}

In this partcular component , my intention is to read both the route parameters(id , pid) and then make a call to service method. But because there are 2 route parameters to read , the service method is called twice.

Any idea what needs to be modified so that service method is called once ?

refactor
  • 13,954
  • 24
  • 68
  • 103

2 Answers2

0

You can use switchMap:

this.route.params
.switchMap(({id, pid}) => appService.GetProduct(id,pid))
.subscribe(data => this.product = data);
undefined
  • 6,366
  • 12
  • 46
  • 90
0

Below text from this link solved my issue.

Right now, if an error happens during detecting changes of content/view children of a component, ngOnInit will be called twice (seen in DynamicChangeDetector). This can lead to follow up errors that hide the original error.

In my case also , there was some other error in my component , which resulted in ngOnInit() executing twice.. hope this will be helpfull to others. I had spent 2 hrs on this issue :(

Community
  • 1
  • 1
refactor
  • 13,954
  • 24
  • 68
  • 103