2017-05-05 152 views
3

我正在使用Angular4和angular-cli重建旧的Web平台(用php编码)。如何在Angular2中将变量值从一个组件传递到另一个组件

我正在寻找一种方式来在组件中一次声明多个变量叫我的配置,这样我可以在其他组件,如我的尺直接使用它们,无需重新声明他们:

我的 - configuration.component.ts

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

@Component ({ 
    selector: 'my-configuration', 
    templateUrl: './my-configuration.component.html', 
    styleUrls: ['./my-configuration.component.css'] 
}) 

export class MyConfigurationComponent { 
    variable1: String; 
    variable2: String; 

    constructor(){ 
     this.variable1 = 'value1'; 
     this.variable2 = 'value2'; 
    } 
} 

我-footer.component.ts

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

@Component ({ 
    selector: 'my-footer', 
    templateUrl: './my-footer.component.html', 
    styleUrls: ['./my-footer.component.css'] 
}) 

export class MyFooterComponent { 
    footer-variable1: String; 
    footer-variable2: String; 

    constructor(){ 
     this.footer-variable1 = //Get the variable1 value from MyConfigurationComponent; 
     this.footer-variable1 = //Get the variable2 value from MyConfigurationComponent; 
    } 
} 

什么是这样做的正确方法?

回答

3

在整个应用程序中共享数据的推荐方式是使用Angular服务。它们被定义为单例,因此您保留的任何值都可用于整个应用程序。

你可以找到更多关于这里的服务:https://angular.io/docs/ts/latest/tutorial/toh-pt4.html

我只是把一个博客帖子和plunker展示如何做到这一点:

http://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/

enter code here 

https://plnkr.co/edit/KT4JLmpcwGBM2xdZQeI9?p=preview

1

看环境/ environment.ts,你可以把你的变量放在那里,或者你可以像这样使用

export const config = { 
    variable1: 'ble', 
    variable2: 'bla' 
}; 
+0

你或许应该冻结对象,使性能不变为好。 –

相关问题