Angular 4 - 如何模拟原型和开发的模拟数据
我正在将AngularJS v1.5项目升级到Angular 4.x。在开发原始AngularJS应用程序的过程中,我们将使用ngMocks
包来模拟实际的Web服务API响应,并在页面上显示相应的数据。这在开发过程中非常有用,因为我以后不需要对值进行硬编码。最重要的是,我们将Webpack配置为在开发过程中仅包含模拟数据,并且在构建我们的应用程序以供生产使用时忽略这些模拟数据文件。模拟数据配置是这样的:那么Angular 4 - 如何模拟原型和开发的模拟数据
/* app-login.mock.js */
import angular from 'angular';
import 'angular-mocks';
angular.module('app').run(function ($httpBackend) {
$httpBackend
.whenPOST('./api/auth')
.respond(function(method, url, data) {
var credentials = angular.fromJson(data);
if (credentials.username == 'gooduser') {
return [200, {'token': createToken(credentials.username)}];
} else {
return [401, {'errorMsg': 'Mock login only allows username "gooduser"'}];
}
});
});
function createToken(username) {
// Create a token, which is valid enough for testing purposes.
// This token is based on the actual token generated by the web service.
let currentTime = new Date();
let futureTime = new Date(currentTime.getTime() + ((currentTime.getHours() + 8) * 60 * 60 * 1000));
let header = {
alg: 'HS512'
};
let payload = {
exp: futureTime.getTime()/1000,
sub: username,
roles: 'SOME_APPLICATION_ROLES',
iat: currentTime.getTime()/1000
};
return `${btoa(angular.toJson(header))}.${btoa(angular.toJson(payload))}`;
}
的WebPack被配置为包括所有“模拟”文件到内置捆绑,就好像它是一个真正的HTTP响应可能随后被显示出来。
/* webpack.config.js */
const isProd = process.env.NODE_ENV === 'production';
const entry = {
app: (() => {
let app = [
'babel-polyfill',
path.join(PATHS.app, 'pollyfills.ts'),
path.join(PATHS.app, 'main.ts')
];
if (isProd) {
app.push(path.join(PATHS.app, 'app.prod.js'));
} else {
app.push(path.join(PATHS.app, 'app.mock.js'));
}
return app;
})()
};
module.exports = {
entry,
// ...other exports
};
然后是app.mock.js
文件:
/* app.mock.js */
var mockContext = require.context(".", true, /\.mock$/);
mockContext.keys().forEach(mockContext);
我已经冲刷互联网寻找的作品一样好,我们的旧的解决方案,虽然我还没有想出什么好答案。我发现的最好的教程是关于如何设置返回模拟数据的单元测试,虽然这对于测试功能非常有用,但它并不能帮助我在开发过程中测试应用程序。
我也看到了有关使用内4角新发现的HttpClient
类设置Interceptors
一些文档,但我不知道如何将它添加到我们的WebPack配置的开发过程中只被允许的情况下。有没有人有什么建议做什么?
我使用角内存中的web-api。你可以在这里找到它:https://github.com/angular/in-memory-web-api
它拦截所有的http调用,并与你提供的示例数据一起工作。
要从dev切换到生产,您需要删除导入。或者你可以编写两个不同的模块,一个使用dev进口,一个使用生产导入,另一个模块包含一个或另一个与webpack相似的模块。 (但我没有试过。)
你建立你的数据是这样的:
import { InMemoryDbService } from 'angular-in-memory-web-api';
import { IProduct } from './product';
export class ProductData implements InMemoryDbService {
createDb() {
let products: IProduct[] = [
{
'id': 1,
'productName': 'Leaf Rake',
'productCode': 'GDN-0011',
'releaseDate': 'March 19, 2016',
'description': 'Leaf rake with 48-inch wooden handle.',
'price': 19.95,
'starRating': 3.2,
'imageUrl': 'http://openclipart.org/image/300px/svg_to_png/26215/Anonymous_Leaf_Rake.png',
'tags': ['rake', 'leaf', 'yard', 'home']
},
// ...
];
return { products };
}
}
你使用普通的HTTP或HttpClient的建立自己的数据访问服务。
我有一个完整的例子在这里所有的CRUD操作:https://github.com/DeborahK/Angular2-ReactiveForms
你试过JSON-服务器。我在我们的应用程序中使用它 – Skeptor
我从来没有听说过它,但我会看看自己。感谢您的建议! –