在Angularjs中将字符串值传递给$ resource

时间:2014-03-26 22:17:29

标签: javascript angularjs

我有以下情况试图完成

使用$ resource我正在调用

App.factory("AppRepository", ['$resource', function ($resource) {  
       return
        checkPerson: $resource('/api/accountAdd/:netName', { name: '@netName' }, { get: { method: 'GET' } })
     }; 
}]);

比我的cotroller我打电话

var netName="Tom"
    AppRepository.checkPerson.get(netName, function (data) {
        alert("success");
    })

这不起作用,因为我正在为netName传递字符串。请告诉我如何将字符串值传递给工厂。我之前曾使用id工作,但它工作正常但不确定如何处理字符串值。 感谢

3 个答案:

答案 0 :(得分:1)

应该是这样的

var netName="Tom"
    AppRepository.checkPerson.get({ netName: value }, function (data) {
        alert("success");
    })

答案 1 :(得分:1)

我相信您的$resource规范不正确。第二个参数是paramDefaults哈希。其中的键必须是URL中占位符的名称,值是表示如何填充占位符的字符串。

App.factory("AppRepository", ['$resource', function ($resource) {  
    return {
        checkPerson:
            $resource('/api/accountAdd/:netName',
                // key states that it will replace the ":netName" in the URL
                // value string states that the value should come from the object's "netName" property
                { netName: '@netName' },
                { get: { method: 'GET' } })
    }; 
}]);

这应该允许您按如下方式使用服务:

var netName="Tom"
AppRepository.checkPerson.get({ netName: netName }, function (data) {
    alert("success");
})

答案 2 :(得分:0)

AppRepository.checkPerson.get({name: netName}, function (data) {
    alert("success");
})

此外,您的工厂定义有错误,you cannot start a new line after a return并且在返回值之前,您的工厂返回undefined。将返回值与return移动到同一行。

编辑:squid314上面的回答是正确的