Angular AoT构建导入本地json文件



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

在开发模式下,当我修改json文件时,cli会重建应用程序,所有这些都像符咒一样工作。不幸的是,在构建时,prod修改我的"dist/assets"目录中的json不会更新应用程序。编译器将json嵌入到我的main-es2015.js中,不再引用外部文件。

工作服务.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')

但是页面是在文件之前加载的,我不知道如何在之前加载它。

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

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

然后导入这个const并将其用于组件中。

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

最新更新