首先,问题标题没有意义。我不确定如何才能更好地提出问题。
我在Angular 8.1项目中遇到问题。在设置类(其服务)中有一个导入文件Im。 当environment.ts文件的变量为app_company时。同名的json文件也可用。因此,如果客户端app_company与json文件匹配。所有配置应从该文件加载。这是我需要实现的 到目前为止,我尝试过的是。
import { Injectable } from '@angular/core';
import { environment } from '@env/environment';
import * as client1 from './client1.json';
@Injectable({
providedIn: 'root'
})
export class SettingsService {
newInstance:object;
constructor() { }
config(key : string){
// const newInstance = Object.create(window[environment.app_company].prototype);
// newInstance.constructor.apply(newInstance);
// return newInstance.key;
// const newInstance: any = new (<any>window)[environment.app_company];
// console.log(Object.create(window[environment.app_company]));
return environment.app_company.key;
}
}
我的json文件如下所示
{
"opNumberLabel" : "OP No"
}
因此在返回部分中,如果我致电client1.opNumberLabel
它的工作方式符合我的期望,但我尝试使这种动态效果像environment.app_company.key
一样无法正常工作。
如您所见,我的尝试已被评论,但到目前为止还没有解决:(。
任何提示将不胜感激。 预先感谢,
答案 0 :(得分:1)
您想实现类似的目标吗?
import { Injectable } from '@angular/core';
import * as settings from "./environment.json";
interface Settings {
[key: string]: string
}
type Environment = {
[key: string]: Partial<Settings>
};
@Injectable({
providedIn: 'root'
})
export class SettingsService {
private environment: Environment = {
app_company: { }
};
constructor() {
this.environment.app_company = settings;
console.log(this.config("opNumberLabel")); // OP No
}
config(key : string){
return this.environment.app_company[key];
}
}
{
"opNumberLabel" : "OP No",
"settings1": "testSettings1",
"settings2": "testSettings2"
}
如果您也想将app_company
作为动态值,那么我建议扩展该示例:
init
函数,该函数也可以接受名称
client
。SettingsService
构造函数,使用InjectionToken
,因此您可以定义什么是
您正在尝试配置的当前客户端。您可能还想为不同的客户端设置不同的环境,所以我建议为每个客户端创建单独的环境json文件。
您可以使用<client>.environment.json
键创建一个可以容纳每个<client>
的对象。
之后,您将拥有一个对象,像这样:
const clientEnvironments: Environment = {
client1: { ... },
client2: { ... }
};
因此,通过使用当前客户端的名称,您可以轻松选择要使用的环境。
答案 1 :(得分:1)
最后我解决了。
android:layout_width="match_parent"
感谢@Titus的提示。