如何创建,使用$资源取决于参数的数据返回服务 [英] How can I create a service that returns data using $resource depending on parameter

查看:117
本文介绍了如何创建,使用$资源取决于参数的数据返回服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建它要求根据参数后端的服务。这code没有工作,但我希望它显示我想达到什么样的:

I want to create a service which calls the backend depending on parameters. This code does not work, but I hope it shows what I would like to achieve:

myproject.factory('Item', function($resource) {
    if (@id !== undefined)
        return $resource('/resource/item/:id/item.json', {id: '@id'});
    else if (@userid !== undefined)
        return $resource('/resource/user/:userid/items.json', {userid: '@userid'});
});

基本上第一个选项只能由它的ID返回一个项目,第二个选项通过用户ID返回几个项目。

Basically the first option only returns one item by its id, the second option returns the several items by userid.

然后,我会希望能够调用该服务是这样的:

I would then like to be able to call that service like this:

$scope.item = Item.get({id: id}, function() {...}

$scope.items = Item.query({userid: userid}, function() {...}

什么是实现类似的东西的最佳方式?我需要的一切创建单独的服务?

What is the best way to achieve something like that? Do I need to create separate services for everything?

谢谢!

推荐答案

您可以使用自定义动作参数替代默认URL // docs.angularjs.org/api/ngResource.%24resource相对=nofollow>看$资源文档

You can override the default URL using custom actions parameter: see $resource docs

我的意思是这样的:

$resource('/resource/item/:id/item.json', {}, {
    query: {
        url: '/resource/user/:userid/items.json',
        method: 'GET',
        isArray: true
    }
});

现在获得()和其他请求都将使用默认的URL,而 .query()应使用自定义网址。

Now .get() and other requests will use the default URL, while .query() should use custom URL.

请注意,网​​址属性角1.2(现在的稳定版本)是新的。

Note that the url property is new in Angular 1.2 (now stable release).

这篇关于如何创建,使用$资源取决于参数的数据返回服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆