1

So, I have a container component "Profile" that has a navigation inside - switching tabs like "Info", "Favourites", "PublishedArticles".

I'm currently loading those tabs with router-outlets and sub-routes lie "/info", "/favourites", "/articles". And once router-outlet navigates to cub-component, I want to pass the slice of the loaded Profile state to it.

I've just realised that the normal @Input wouldn't work for loading dumb components in such a way (via router-outlet). And now I'm looking for solution to implement it in a somehow neat way without too much restructuring.

What would be the best way to communicate state to the dumb components (child routes) loaded by the router-outlet? Or, possibly, how you would normally approach such scenario in general?

  • Have a look at [this one](http://stackoverflow.com/questions/35478994/angular-2-passing-object-via-route-params-possible). Using providers to share data across `Components` – John Dec 25 '16 at 13:58
  • Seems like the general way to approach this is to either (a) create a shared service between the components and have variables data bound between them, or if you don't need databinding: (b) pass values via route params – jarodsmk Feb 21 '17 at 07:25

1 Answers1

0

I would make a Service that is injected into all components sharing the same data, like this one:

@Injectable()
export class SharedDataService {
  someData:Object={}
  constructor() {

  }
}

Then, in your components, you can listen for a navigation change using the Router Service in order to update your data in your component and UI.

import {Component,OnInit} from '@angular/core';
import {NavigationEnd, Router} from "@angular/router";
import {SharedDataService} from "../shared-data.service";
@Component({
  selector: 'profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})
export class Profile implements OnInit {
  someData:Object;

  constructor(private sharedDataService: SharedDataService, private router:Router) {
    this.someData = this.sharedDataService.someData;
    this.router.events.subscribe((val)=>{
      if(val instanceof NavigationEnd){
          //update the shared data when this page is being navigated to
          this.someData=this.sharedDataService.someData;
      }
    });
  }
}
John
  • 10,165
  • 5
  • 55
  • 71