问题
I want my angular app to work as a Standalone without a server.
In the assets folder are images, sound-files etc. and one game.json file which contains the business data for the application (On a server this data would be stored in a DB or would be called via Rest).
Everything works quite well. Using 'ng build' I can create the complete build which can be startet by opening the index.html in my OS - file manager without a http-Server.
The problem is that I can't change the content of game.json after the build, because it seems to be included in the build in some way. Changes are ignored, it freezes the content in state it was compiled.
Since I will run the app only locally I read my data this way:
typings.d.ts:
declare module "*.json" {
const value: any;
export default value;
}
game.service.ts:
import * as data_json from 'assets/data/game.json';
@Injectable()
export class GameService {
constructor() { }
loadGames(): Observable<Game> {
return Observable.of(JSON.parse(JSON.stringify(data_json)));
}
}
I don't use HTTPClient because I would run into CORS problems. Reading the data works fine, but changes in the file game.json are ignored completely.
Is there a way to make this file "modifyable" so I can change it in the assets folder of the build?
回答1:
You can get data from assets folder like shown below and you can also change it run time.
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
@Injectable({
providedIn: "root"
})
export class GameService {
private gameData: any;
constructor(private http: HttpClient) {}
loadGameData() {
return this.http
.get("/assets/data/game.json")
.toPromise()
.then(data => {
this.gameData= data;
});
}
get gameData() {
if (!this.gameData) {
throw Error("Game file not loaded!");
}
return this.gameData;
}
}
app.module.ts changes:
import { NgModule, APP_INITIALIZER } from "@angular/core";
import { GameService } from "./services/GameService.service";
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [
[
{
provide: APP_INITIALIZER,
multi: true,
deps: [GameService],
useFactory: (gameService: GameService) => {
return () => {
return gameService.loadGameData();
};
}
}
]
],
bootstrap: [AppComponent]
})
来源:https://stackoverflow.com/questions/55296737/angular-changing-data-in-assets-folder-of-the-build