1
votes

In my angular app. I am navigating from secondComponent to firstComponent and transferring the data using Router. I am able to do it successfully. After routing to the firstComponent, i want to implement some logic. I do not have any click events to implement the logic. As the firstComponent i am routing to is already initialized and rendered. Which type of method or a life cycle event can i use to implement the logic. I have tried to put the logic in constructor but it throws me an error as the method is implemented before navigating to the component ans the variable is not intialized.

FirstComponent

 constructor(private route: Router,
              private router: ActivatedRoute) {

  this.router.params.subscribe(data => {
      this.Search(data);
    });

Search(data) {
    this.source.addFilter({field: 'test', search: data.testValue});
  }
}

SecondCompoennt

 ngAfterViewInit() {
    this.searchService.onSearchSubmit()
      .subscribe((data: any) => {
        const testValue = data.term;
        this.route.navigate(['/test/path', {testValue}]);
      });
  }
1

1 Answers

2
votes

You should move logic from the consturctor to the ngOnInit lifecycle hook. If the class is instanciated at the time the constructor is called, variables depending on external sources might not been initialized yet. That's why it's a good practice to leave the constructor's body empty and use lifecycle hooks to handle the logic.