gpt4 book ai didi

angularjs - 如何在 AngularJS 中创建模拟后端?

转载 作者:行者123 更新时间:2023-11-28 19:41:22 25 4
gpt4 key购买 nike

如何实现模拟后端以使用 AngularJS 进行快速原型(prototype)制作?

我需要能够伪造响应延迟、响应数据等。

我使用 $http 服务。

最佳答案

您可以使用 Angular 模拟来提供模拟后端。

工作演示 plnkr .

基本上,您在 angular 之后包含 angular-mocks,并使用 this gist 中提供的代码并且您将能够控制请求和响应,包括 header 和假响应延迟等。

例子:

    //When backend receives a request to the views folder, pass it through
$httpBackend.whenGET( RegExp( regEsc( Config.view_dir ) ) ).passThrough();

//Message should return a list og messages
$httpBackend.whenGET(APIBase + 'messages').respond(function(method, url, data, headers) {
return [200, messages.data, {/*headers*/}];
});

$httpBackend.whenPOST(APIBase + 'messages').respond(function(method, url, data, headers) {
var message = angular.fromJson(data);

messages.data.push(message);
//You should consider having the back-end being responsible for creating new id tho!
messages.index[message.id] = message;

return [200, message, {/*headers*/}];
});

//Message/id should return a message
$httpBackend.whenGET( RegExp(regEsc(APIBase + 'messages') + '\d+$') ).respond(function(method, url, data, headers) {
var id = url.match(/\d+$/)[0];
return [200, messages.index[id] || null, {/*headers*/}];
});

```

您还可以设置应该传递给实际服务器的 url(检查 passThrough())

关于angularjs - 如何在 AngularJS 中创建模拟后端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20350681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com