服务和控制器使用api末尾的值调用api(Service and Controller to call api with a value in the end of api)

编程入门 行业动态 更新时间:2024-10-06 10:26:02
服务和控制器使用api末尾的值调用api(Service and Controller to call api with a value in the end of api)

我有一个服务调用,我想将值传递给函数以通过id调用http.get api:

/home/api/order/1

我的服务看起来像这样:

angular.module("app") .factory('Service', ['$http', function ($http) { var urlBase = '/home/api/order/'; Service.getOrderbyorderid = function (orderid) { return $http.get(urlBase + orderid) }; });

我为我的控制器试过的是:

getOrderbyorderid (); function getOrderbyorderid () { $scope.orderid = $routeParams.orderid ; console.log($scope.orderid); //Sees ID Service.getOrderbyorderid ($scope.orderid ) .success(function (response) { $scope.ordertest = [] $scope.ordertest = response.data; console.log($scope.ordertest ); //Undefined }) };

有人可以帮我调用控制器,所以我可以用特定的orderid调用api吗?

我得到的错误

我什么时候得到一个未定义的

console.log($scope.ordertest),

但我看到了我的身份

console.log($scope.orderid);

I have a service call that I want to pass a value into the function to call the http.get api by id:

/home/api/order/1

My service looks like this:

angular.module("app") .factory('Service', ['$http', function ($http) { var urlBase = '/home/api/order/'; Service.getOrderbyorderid = function (orderid) { return $http.get(urlBase + orderid) }; });

What I have tried for my Controller is:

getOrderbyorderid (); function getOrderbyorderid () { $scope.orderid = $routeParams.orderid ; console.log($scope.orderid); //Sees ID Service.getOrderbyorderid ($scope.orderid ) .success(function (response) { $scope.ordertest = [] $scope.ordertest = response.data; console.log($scope.ordertest ); //Undefined }) };

Question

Can someone help me in calling the controller right so I can call the api with a specific orderid?

Error I am getting

I am getting an undefined when I

console.log($scope.ordertest),

but I see the id when I

console.log($scope.orderid);

最满意答案

你应该使用.success而不是.success 。 从角度文档 :

$ http遗留承诺方法成功和错误已被弃用。 请改用标准方法。 如果$ httpProvider.useLegacyPromiseExtensions设置为false,则这些方法将抛出$ http / legacy错误。

.success方法破坏.success的响应对象:

Service.getOrderbyorderid($scope.orderid) // .success(function (data) { .then(function (response) { $scope.ordertest = response.data;

You should use .then rather than .success. From the angular docs:

The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.

The .success method destructs the response object for .then:

Service.getOrderbyorderid($scope.orderid) // .success(function (data) { .then(function (response) { $scope.ordertest = response.data;

更多推荐

本文发布于:2023-08-07 17:15:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465223.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:末尾   控制器   api   call   Service

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!