Angular AoT构建导入本地json文件

时间:2019-11-01 10:11:01

标签: json angular import build aot

在我的第一个有角度的应用程序中,我有一个服务,该服务导入json文件以加载一些数据(我需要在DOM之前同步加载它)。

在开发模式下,当我修改json文件时,cli重建了该应用程序,所有工作都像一个魅力。 不幸的是,在 build -prod 上修改“ dist / assets”目录中的json不会更新应用。编译器将json嵌入我的main-es2015.js中,并且不再引用外部文件。

works.service.ts

import { Injectable } from '@angular/core';
import PICTURES  from '../../assets/pictures.json';

@Injectable({
  providedIn: 'root'
})
export class WorksService {
    pictures: any;

    constructor() {
      this.pictures = PICTURES
    }

    getWorks() { return this.pictures; }

    getSingleWork(id: string) { 

      return  this.pictures.find(i => i.id === id);}

    getPreviousWork(id: string) { 

      const index = this.pictures.findIndex(i => i.id === id) - 1;

      if (typeof this.pictures[index] === 'undefined') {
        // cycle to start
        return this.pictures[this.pictures.length-1]
      }
      else {
        return this.pictures[index]
      }
    }

    getNextWork(id: string) { 

      const index = this.pictures.findIndex(i => i.id === id) + 1;

      if (typeof this.pictures[index] === 'undefined') {
        // cycle to start
        return this.pictures[0]
      }
      else {
        return this.pictures[index]
      }
    }
}

我尝试使用httpClient或动态加载json:

this.pictures = import('../../assets/pictures.json')

但是页面是在文件之前加载的,我无法弄清楚如何在文件之前加载。

1 个答案:

答案 0 :(得分:0)

最好创建一个新的pictures.ts文件,然后将JSON作为对象放入该文件中。

// pictures.ts
export const pictures: any = { "name":"John", "age":30, "car":null };

之后,导入该const并将其用于您的组件中。

// pictures.component.ts
import { pictures } from "./pictures";