在我的第一个有角度的应用程序中,我有一个服务,该服务导入json文件以加载一些数据(我需要在DOM之前同步加载它)。
在开发模式下,当我修改json文件时,cli重建了应用程序,所有工作都像一个超级按钮。不幸的是,在build -prod上修改我的'dist'目录中的json不会更新该应用程序。我想AoT会将json编译为代码,并且不再在外部文件上引用了?
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')
但是页面是在文件之前加载的,我无法弄清楚之前如何加载它。
最好创建一个新的pictures.ts
文件,并将您的JSON作为对象放入该文件中。
export const pictures: any = [{}];
在导出此const并将其用于您的组件之后。
import { pictures } from "./pictures";