简体   繁体   English

将数据传递到所有组件| 角度4

[英]passing data to all component | angular 4

I have component has array and I want to pass this object to all other components. 我有组件具有数组,我想将此对象传递给所有其他组件。 in my component I have a function gets the data based on the cookie value then I want to put the object data in other components {{lang.data1}}. 在我的组件中,我有一个函数根据cookie值获取数据,然后将对象数据放入其他组件{{lang.data1}}中。

    this.lang=this._webService.getlang(this.cookieValue);

how can I use lang in all other component. 我如何在所有其他组件中使用lang。

You may use dependency injection and inject language service or you can you BaseComponent 您可以使用依赖项注入和注入语言服务,也可以使用BaseComponent

export class BaseComponent {

    public language: any;

    constructor() {
        this.language = configuration.language;
    }
}
export class BlockComponent extends BaseComponent {
    constructor() {
        super();
        console.log(this.language);
    }
}

Use the component with array as a service. 将带有数组的组件用作服务。 Initialize that service in the root component and import that service array at any component you want. 在根组件中初始化该服务,然后在所需的任何组件处导入该服务数组。

If this is for a Small to medium Scale application 如果这是中小型应用程序

then you make you services inorder to pass information to all the components using Event Emitters 然后您使服务成为可能,以便使用事件发射器将信息传递给所有组件

But if this is for a large application i would recommend you to user ngrx i:e redux approach where all the data is stored at a particular location. 但是,如果这是用于大型应用程序,我建议您使用ngrx i:e redux方法,其中所有数据都存储在特定位置。

If you want to check how redux works please look at this repo in git hub has a very simple demo on ngrx store with angular. 如果要检查redux的工作方式,请在git hub中的这个仓库上查看有关ngrx store的一个非常简单的演示。

https://github.com/rahulrsingh09/AngularConcepts https://github.com/rahulrsingh09/AngularConcepts

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

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