Shawn
Shawn

Reputation: 5260

angular 2 passing parameters through service rather than router parameters

When passing parameters from component to component, we can use the following

  onSelect(hero: Hero) {
    this.router.navigate( ['HeroDetail', { id: hero.id }] );
  }

But when the data to be passed around is complex then the above will make the URL looked messy. I tried to pass parameters through a service at parent level and it works fine. Then onSelect() becomes

  onSelect(hero: Hero) {
    this._heroService._dataStore.hero = hero;
    this.router.navigate( ['HeroDetail' );
  }

In the ngInit() I retrieved id from this._heroService._dataStore.hero.id. This make the URL much cleaner.

My questions is that is there any downside of this approach? If yes what do people get around those cons?

Upvotes: 1

Views: 484

Answers (1)

inoabrian
inoabrian

Reputation: 3800

I think one downside would be that you won't be able to refresh the page and persist the data like you would if it were a url parameter.

Upvotes: 1

Related Questions