如何使用常量在以角度 7 编码的 UI 中显示标签



我想在我的页面上显示一些常量/属性/json文件中的标签。有人可以建议如何在角度 7 中实现这一点。

目的是当用户想要更改文本时,html中的标签之一,而不是在html文件中更改它,我应该能够在常量/json/properties文件中进行更改,并且相同的内容将反映在所有html页面中。 例如,{{lblManage}} 在其他一些文件中,lblManage = Manage Task。

Angular 自动提供环境常量文件

/YourApp/src/environment/environment.ts ->用于非生产,比如简单使用 ng serve。

/YourApp/src/environment/environment.prod.ts -> 用于生产,使用 ng build --prod

例如,环境.ts

export const environment = {  
production: false,
apiUrl: 'http://example.com/api'
};

您可以简单地在其中添加属性,并在以后的整个代码中使用它们,如下所示:

import { environment } from './environment';
...
apiURL = environment.apiUrl;

你可以像这样读取你的 json 文件:

import { HttpClient } from '@angular/common/http'; 
import { Observable } from 'rxjs';
@Injectable()
export class readJSONService{
constructor(private http: HttpClient) {
this.readJSON().subscribe(data => {
console.log(data);
});
}
public readJSON(): Observable<any> {
return this.http.get("./assets/constants/properties/json");
}
}

然后像这样使用创建的服务。

label: any;
constructor(private readJSONService: readJSONService) {
this.label = this.fetchConstant(lblMAnage);

}

fetchConstant(lblMAnage){
this.readJSONService.readJSON().subscribe((yourLabel)=> {
console.log(yourLabel);
this.label = yourLabel.lblMAnage;
});
}

回答第二部分

目的是当用户想要更改文本时,html中的标签之一,而不是在html文件中更改它,我应该能够在常量/json/properties文件中进行更改,并且相同的内容将反映在所有html页面中。例如,{{lblManage}} 在其他一些文件中,lblManage = Manage Ta如前所述,可以在 environment.ts 文件中声明先前的常量,如果要对其进行更改,请使用 **store 概念 ** 。其中,变量存储在环境中文件可以存储在存储中并根据请求进行更新。

减速器文件:

export interface ConstantState {
url: any
}

export const initialState: ConstantState = {
url:'http://hello.com'
}
export function constantReducer(
state: constantState = initialState,
action: constantAction
): BookingState {
switch (action.type) {
case 'GET_STATE': {
state = {
...state,
};
break;
}
case 'SET_STATE': {
return {
...state,
url:action.payload
};
break;
}
}
return state;
}

文件记录

从"@ngrx/商店"导入 { 操作 };

export enum COnstantActionTypes {
GetCOnstant = '[Constant] Get',
SetConstant = '[Constant] Set'
}
export class GetCOnstant implements Action {
readonly type = COnstantActionTypes.GetCOnstant;
}
export class SetConstant implements Action {
readonly type = COnstantActionTypes.SetConstant;

构造函数(有效负载:任何){} }

export type COnstantAction = GetCOnstant | SetConstant;

创建选择器 const getConstantState = createFeatureSelector('constatentState');

因此,我们可以在更新常量时在所需页面上调度操作,并且要获得,我们可以使用 选择器方法 .此外,常量意味着我们不能改变值,所以我们必须相应地命名

如果您想从某些常量/属性/json 文件在我的页面上显示标签,那么只需使用环境文件夹下的环境文件,或者如果首选国际化,则 i18n。

然后通过在组件中使用导入,例如,如果我们使用第一种方法

import { environment } from './environment';

并访问它作为

environment.constant_name

最新更新