2017-09-21 28 views
2

我有一些字符串常量值,它必須在許多組件中使用。我不想硬編碼或將它們寫入單個組件中的字符串。 哪裏是最好的地方來維護他們在angular2應用程序?angular2很多字符串值存儲

回答

1

有沒有這樣的東西稱爲常量或配置像angularJs 1在角度。

所以我會說要做一個飛機班,把所有的字符串放在那裏。你可以讓它們成爲靜態的,以便直接用類名訪問它們。

export class StngsValue { 
    static finrstWord = 'this is test string'; 
    static secoundWord = 'this is test string'; 
    static thirdWord = 'this is test string'; 
} 

或者你可以把你所有的字符串一個JSON文件,並從一個角度服務調用josn文件中像這樣

@Injectable() 
export class ConfigService { 
    public config: any; 
    private configObs: Observable<any>; 

    constructor(private http: Http) { 
    } 

    public load(): Observable<any> { 
    if (this.config) { 
     return Observable.of(this.config); 
    } else { 
     this.configObs = this.http.get('/configuration.json').map((res) => { 
     this.config = this.config || res.json() || {}; 
     return this.config; 
     }); 
    } 

    return this.configObs; 
    } 
} 
1

解決的辦法之一是把你的字符串中的共享服務。在需要該屬性的每個組件中注入服務。如果你的字符串不是一個常量而且字符串值可能會被更新(這不是你的情況,我猜)。

一種其他的方法是將聲明一個 '普通的' 類打字原稿,* .TS文件,像這樣:

export const CONFIG = Object({ 
    MYSTRING: 'Hello', 
... 
)} 

然後用它在組件(舉例來說):

import { CONFIG } from 'shared/config'; 

    myString = CONFIG.MYSTRING; 

這是很好的將所有常量分組在一個地方。

您也可以選擇去一個常數:

export const MyString = "Hello"; 

然後你就可以在你的組件導入爲先。

0

您可以使用共享服務並將其設置爲單例,以便您的所有組件都能夠訪問該服務中的數據/方法/等。所以你只需要聲明的文件作爲

shared.service.ts 

內:

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

@Injectable() 
export class SharedService{ 

    public str: string; 

} 
在app.module.ts

導入服務和@ngModule,在供應商地址:

providers: [ SharedService ] 

然後在您的任何組件中只需導入服務,並在組件構造器中添加:

constructor(public service: SharedService){} 

這裏您注射的服務爲您的組件,你可以閱讀有關dependecy注射

現在你可以用this.service.string

訪問字符串