如何嘲笑获得(ID)的请求ID

由网友(想在江湖混,最好是光辊↘)分享简介:我建立一个应用程序的原型,并尝试嘲笑REST的Web服务。I am building an application prototype and try to mock the REST web-services.下面是我的code:var mock = angular.module('mock', ['ngMoc...

我建立一个应用程序的原型,并尝试嘲笑REST的Web服务。

I am building an application prototype and try to mock the REST web-services.

下面是我的code:

var mock = angular.module('mock', ['ngMockE2E']);
mock.run(function($httpBackend){
    users = [{id:1,name:'John'},{id:2,name:'Jack'}];
    $httpBackend.whenGET('/users').respond(users);
    $httpBackend.whenGET(new RegExp('/users/[0-9]+')).respond(users[0]);
}

一切正常,我的资源User.query()返回所有用户,User.get({ID:1})和User.get({ID:2})。返回相同的用户(约翰)

Everything is ok, my resource User.query() returns all users, and User.get({id:1}) and User.get({id:2}) returns the same user (John).

现在,以提高我的原型,我想回相应的用户,匹配良好的ID。

Now to improve my prototype, I would like to return the appropriate user, matching the good id.

我角文档我应该能够取代正则表达式URI由函数。这个想法是从URL中respond方法用它提取的ID。然后,我尝试这样的:

I read in the angular documentation I should be able to replace the RegExp URI by a function. The idea is to extract the id from the url to use it in respond method. I then tried this:

$httpBackend.whenGET(new function(url){
    alert(url);
    var regexp = new RegExp('/users/([0-9]+)'); 
    id = url.match(regexp)[1];  
    return regexp.test(url);
}).respond(users[id]);

问题是URL参数总是不确定的。任何想法来实现我的目标?

The problem is the url parameter is always undefined. Any idea to achieve my goal?

推荐答案

我发现了一个解决方案,通过在部分响应,而不是部分时,使用功能:

I found a solution by using a function in the respond part instead of the when part:

$httpBackend.whenGET(new RegExp('/users/[0-9]+')).respond(
    function(method, url){
        var regexp = new RegExp('/users/([0-9]+)');
        var mockId = url.match(regexp)[1];
        return [200, users[mockId]];
    }
});
阅读全文

相关推荐

最新文章