[英]What's the best way to create a dummy $resource for development purposes in Angular?
I'm developing an Angular app (actually, an Ionic app) that relies on a REST API. 我正在开发依赖REST API的Angular应用程序(实际上是Ionic应用程序)。 To communicate with the API, I will inject
$resource
s into my controllers. 为了与API通信,我将
$resource
注入到控制器中。
I want to focus on the app now, and worry about the backend later—so I'd like to create dummy versions of my various $resource
s. 我现在想专注于应用程序,以后再担心后端—因此,我想为我的各种
$resource
创建虚拟版本。 For example, my dummy Products
$resource will contain a few sample product records (hardcoded as JSON), and will support/mimic the same CRUD operations that the real $resource
will eventually support. 例如,我的虚拟
Products
$ resource将包含一些示例产品记录(硬编码为JSON),并且将支持/模仿实际 $resource
最终将支持的相同CRUD操作。
In other words, it will be similar to this —but will mimic the same API as $resource
(promises, error handling, etc.). 换句话说,它与此类似,但是将模仿与
$resource
相同的API(承诺,错误处理等)。
Obviously, I could roll my own solution to this—but surely this is already a solved problem. 显然,我可以针对此问题推出自己的解决方案-但可以肯定的是,这已经解决了。 What's the standard approach?
标准方法是什么?
(I've done a fair bit of Googling around this, but everything I find talks about unit testing and test frameworks—which I know little about. Anyway, that seems like a slightly different problem than the one I'm trying to solve. I've also seen a lot about $httpBackend
—but (1) that mocks the lower-level $http
service, not $resource
, which is what I need, and (2) it seems to be meant for use in the context of unit tests, which is not what I'm trying to do.) (我在这方面做了大量的Google搜索,但是我发现的所有内容都涉及单元测试和测试框架,而我对此几乎一无所知。无论如何,这似乎是一个与我要解决的问题略有不同的问题。我还看到了很多有关
$httpBackend
-但是(1) $httpBackend
了较低级别的$http
服务,而不是$resource
,这是我所需要的,并且(2)它似乎是要用于单元测试,这不是我想要做的。)
I finally found an example of using $httpBackend
without a unit test . 我终于找到了一个在没有单元测试的情况下使用
$httpBackend
的示例 。
Essentially, you can inject $httpBackend
into the run()
method of your module, like this: 本质上,您可以将
$httpBackend
注入模块的run()
方法中,如下所示:
app.run(function($httpBackend) {
var phones = [{name: 'phone1'}, {name: 'phone2'}];
$httpBackend.whenPOST('/phones').respond(function(method, url, data, headers){
console.log('Received these data:', method, url, data, headers);
phones.push(angular.fromJson(data));
return [200, {}, {}];
});
$httpBackend.whenGET('/phones').respond(function(method,url,data) {
console.log("Getting phones");
return [200, phones, {}];
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.