Angular Passing Data Between Routes

Kenry Sanchez picture Kenry Sanchez · Apr 5, 2018 · Viewed 43.5k times · Source

I have a little problem using routes in angular 4. You know, when I am trying to pass data from a component to another using navigate('root', data), I just received [object Object],[object Object],[object Object].

Component

export class FillRequestComponent implements OnInit {

  constructor(private route: Router, private dataRoute: ActivatedRoute) { }

  ngOnInit() {
    const key: Products = this.dataRoute.snapshot.params['objectProducts'];
    console.log(key);
  }

Interface

export interface Products {

  color: string,
  question: string,
  surname: string,
  icon: string,
  selected: boolean,
  transparent: boolean
}

Send Method

const data = {
      category: this.optionSelected,
      objectProducts: this.optionSelected === 'CREDIT' ? this.productCreditList :
        this.productAccountsList
    };

    this.route.navigate(['/requests/fill', data]);

Answer

mtpultz picture mtpultz · Feb 26, 2019

In the current version this is now available in @angular/router.

Angular 7.2 introduces route state to NavigationExtras, which takes an object literal similar to queryParams, etc.

The state can be set imperatively:

this.router.navigate(['example'], { 
  state: { example: 'data' } 
});

or declaratively:

<a routerLink="/example" [state]="{ example: 'data' }">
  Hello World
</a>

And read in a top-level component using:

this.router.getCurrentNavigation().extras.state;

or within child components using:

window.history.state

Added a working example of it being used on StackBlitz