繁体   English   中英

什么是将数据传递到其他组件的最佳方法

[英]What is the best way pass data to other components

我正在尝试将用户信息对象传递给所有低级组件,问题是,即使他们是孙辈,将信息传递给情人组件的最佳方法是什么? @input是否可以工作或有其他方法可以传递它?

我的根组件代码是:

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

  }

您是否考虑过创建服务类? 它们是单例,因此该类的相同实例被注入到每个需要它的组件中。

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

一个简单的看起来像这样

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

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

然后将其添加到这样的组件中。

import {DummyService} from 'dummy.service';

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

在运行时,这会将类的相同实例注入到您将其注入到的每个组件中。 因此,这是在多个组件之间同步数据的超级方便的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM