Vitaly Menchikovsky Vitaly Menchikovsky - 1 month ago 8
TypeScript Question

What is the best way pass data to other components

I am trying to pass user info object to all low level component,
the issue is what is the best way to pass it to lover component even if they are grandchildren?
If the @input will work or have anther way to pass it?

my code for root component is:

constructor(private _state: GlobalState,
private _imageLoader: BaImageLoaderService,
private _spinner: BaThemeSpinner, public af: AngularFire) {

this._loadImages();

this._state.subscribe('menu.isCollapsed', (isCollapsed) => {
this.isMenuCollapsed = isCollapsed;
});

// this.af.auth.subscribe(
// user => this._changeState(user),

this.af.auth.subscribe( user => this._changeState(user));

}

Answer

Have you considered creating a service class? They're singletons, so the same instance of that class gets injected into each and every component that asks for it.

https://angular.io/docs/ts/latest/guide/dependency-injection.html

A simple one would look like this

import { Injectable } from '@angular/core';

@Injectable()
export class DummyService {
    public userInfo: UserInfo = {
        //User stuff goes here
    };
}

And you would add it to a component like this.

import {DummyService} from 'dummy.service';

@Component({
  selector: 'my-component',
  templateUrl: 'my.component.html'
})
export class MyComponent{
  constructor(private myDummyService: DummyService){}
}

At runtime, this would inject the same instance of the class into every component you inject it into. So it's a super handy way of syncronizing data across multiple components.

Comments