简体   繁体   English

为 Angular 导入模拟数据

[英]Importing Mock data for Angular

So I am conditionally including an HTTPInterceptor into my application to provide mock data in the mock environment (the app.module.ts includes this:所以我有条件地在我的应用程序中包含一个 HTTPInterceptor 以在模拟环境中提供模拟数据(app.module.ts 包括这个:

import { fakeBackendProvider } from './mock-backend/fake-bakend';

// Snip

if (environment.mock) {
  // used to create fake bakend
  providers.push(fakeBackendProvider);
}

and I am wondering the best way to include the mock data (which is just json files) in fake backend.我想知道在假后端中包含模拟数据(只是 json 文件)的最佳方法。 Currently I am just importing them in the top as it is easiest with the least amount of code:目前我只是在顶部导入它们,因为它最简单,代码量最少:

import * as fakeData from './data.json';

however I am want to be sure that when the environment.mock is set to false and the project is built, this code will get properly tree shocken and not included in the dist.但是我想确保当 environment.mock 设置为 false 并构建项目时,此代码将得到正确的树冲击并且不包含在 dist 中。 Is it better to conditionally import the when I need it在我需要时有条件地导入更好吗

import('./data.json').then(fakeData => {

});

This is slightly more complicated because I can't just use Observable.of and requires a few more lines of code (not a big deal, but there is a bunch of these fake data json files) or will this get included in the single dist file as well and I have to actually use the httpClient to load the data from the assets directory?这稍微复杂一些,因为我不能只使用 Observable.of 并且需要多几行代码(没什么大不了的,但是有一堆这些假数据 json 文件)或者这是否会包含在单个 dist 中文件以及我必须实际使用 httpClient 从资产目录加载数据?

What is the best practice here, or at least the practive that won't end up with my mock data getting bundled with production?这里的最佳实践是什么,或者至少不会使我的模拟数据与生产捆绑在一起的实践是什么?

I would simply use an http.get() and load json result on the fly, like this:我会简单地使用http.get()并动态加载 json 结果,如下所示:

this.http.get('./assets/data.json').subscribe(data => {
  // lets assume you have a service for storing your mock data called "fakeDataProvider"
  this.fakeDataProvider.push(data);
});

If however you need to load json data before the bootstrap of your application, you can always use javascript fetch() :但是,如果您需要在应用程序引导之前加载 json 数据,您始终可以使用 javascript fetch()

fetch('./assets/config.json')
.then(response => {
  return response.json().catch(error => {
    return Promise.reject(new BootstrapError(error, response));
}).then(config => {
  // set a global variable in your application
})

By loading them via an HTTP request you can be sure those data will not be included in the production bundle.通过 HTTP 请求加载它们,您可以确保这些数据不会包含在生产包中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM