Angular2 using @Input with router-outlet. Handling routed dumb components in ngrx/store

1.3k views Asked by At

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?

1

There are 1 answers

0
John On

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;
      }
    });
  }
}