从角度为4

时间:2017-11-15 13:58:08

标签: json angular

我的Angular 4应用程序中有一组组件,其中包含每个组件 需要来自其模板上显示的不同JSON文件的特定属性集。 我创建了一个包含所有属性的公共JSON文件,并在使用包含这些属性数组的服务调用app-component时加载它。

然后我将相同的服务注入不同的组件并获取填充的数组。 HTML中显示的值都很好。

然而,这种方法似乎有点耗时,特别是当常数增加时。一次加载数千个常量并将它们注入不需要其中很少需要的组件并不是一个好方法。

我愿意开发一种方法,我为每个组件创建特定的contansts JSON文件,并在组件实际初始化时以某种方式加载它。这样我就可以节省沉重的JSON对象的负担,只加载那些组件所需的属性。

我的常量服务中的load()方法看起来像这样:

@Injectable()
export class ConstantsService {
constructor(private http: HttpClient) {
    console.log('ConstantsService created');
}
    constants = {};
    load() {
        var constants = {};
        var cons = 'constants';

        var constantsResourceUrl =
            'path' + cons + '.json';

        this.http.get(constantsResourceUrl)
            .subscribe(result => {
                this.constants = result;
            },
            error => this.log.error(constantsResource + ' could not be loaded')
            );
    }
}

我的组件看起来像这样得到常量的值:

@Component({
  selector: 'xyz',
  templateUrl: './xyz.html',
  styleUrl: './xyz.css'
})
export class MyComponent {
  consts = {};

  constructor(private constantsService: ConstantsService) {

    consts = this.constantsService.constants;
  }
}

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

如果确实有类似的困境。使用db或json文件进行设置/参数化行为。动态内容最终在db中,最后我发现获取并使用http请求来获取静态json内容是愚蠢的,因为它可以捆绑在源代码中。我确实拆分它并在ts中使用多个导出的常量。文件如:

export const dummyLookupConst =`{     " queryNo":0,     " id":250, ...}

然后根据需要将其导入组件。