How do I pass data to Angular routed components?

前端 未结 16 1301
挽巷
挽巷 2020-11-22 08:03

In one of my Angular 2 routes\'s templates (FirstComponent) I have a button

first.component.html

16条回答
  •  情深已故
    2020-11-22 08:41

    I looked at every solution (and tried a few) from this page but I was not convinced that we have to kind of implement a hack-ish way to achieve the data transfer between route.

    Another problem with simple history.state is that if you are passing an instance of a particular class in the state object, it will not be the instance while receiving it. But it will be a plain simple JavaScript object.

    So in my Angular v10 (Ionic v5) application, I did this-

    this.router.navigateByUrl('/authenticate/username', {
        state: {user: new User(), foo: 'bar'}
    });
    

    And in the navigating component ('/authenticate/username'), in ngOnInit() method, I printed the data with this.router.getCurrentNavigation().extras.state-

    ngOnInit() {
        console.log('>>authenticate-username:41:',
            this.router.getCurrentNavigation().extras.state);
    }
    

    And I got the desired data which was passed-

提交回复
热议问题