【发布时间】:2019-08-20 13:15:48
【问题描述】:
以前我在 Angular js 中通过一些服务传递 url。现在我想将 url 作为参数从控制器传递给 $resource。
我试图将 url 从控制器传递给资源,但它抛出了找不到 url 对象的错误。
以下是我目前的工厂代码:
angular.module('Services').factory('PatientsService', ['$resource', 'Service', '$http',
function(Resource, Service, Http) {
return {
testGetPatients : Resource(Service.getPatientsCustomRefURL(), {}, {
query : {
method : 'GET',
isArray : false
}
})
};
}]);
在上面的代码中,我从 Service.getPatientCUstomRefURL
发送 url 参数对 $resource 的实际调用如下所示:
PatientsService.getPatientsRef.query(function(refResponse) {
//TODO for response
});
现在我想传递这样的参数:
PatientsService.getPatientsRef.query("/patient/list",function(refResponse) {
//TODO for response
});
我应该在我的 PatientService 工厂中进行哪些更改,以便它支持将 url 作为参数传递。
这里是为 $resource 创建 url 的代码 服务代码
angular.module('Services', ['ngResource']).factory('Service', ['$resource', '$location', '$rootScope',
function($resource, $location, $rootScope) {
return {
getPatientsCustomRefURL: function() {
return '/patient/list';
}
};
}
]);
注意
我在 PatientService 中有这么多方法,所以我不想在 PatientService 中为每个 $resource 添加额外的函数,它将 url 作为参数传递,如
angular.module('Services').factory('PatientsService', ['$resource', 'Service', '$http',
function(Resource, Service, Http) {
return {
testGetPatients : function(url){
return Resource(url, {}, {
query : {
method : 'GET',
isArray : false
}
})
}
};
}]);
【问题讨论】:
-
Service.getPatientsCustomRefURL()返回的值是多少?你能在返回之前做一个console.log(Service.getPatientsCustomRefURL())并检查值吗 -
Service.getPatientsCustomRefURL() 将返回一个字符串 url
-
你能和
console.log联系吗?也许它返回一个承诺或未定义 -
@Fraction 我通过添加 Service.getPatientsCustomRefURL() 代码更新了我的问题。并感谢您的快速回复
-
@Fraction 哎呀,我复制了场景以展示整个项目的演示。你是对的,它应该是服务中的 getPatientCUstomRefURL。再次更新问题。现在你找到完美的场景了吗?感谢回复
标签: angularjs angularjs-service ngresource