2017-05-05 156 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

你或許應該凍結對象,使性能不變爲好。 –

相關問題