从angularjs调用REST API的最佳方式吗? [英] Best way to invoke Rest APIs from angularjs?

查看:230
本文介绍了从angularjs调用REST API的最佳方式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从哪里应该REST API请求,从角JS调用

即。从控制器,模块,服务,factory.I我完全搞不清什么应该是正确的做法呢?

推荐答案

您可以使用资源,或建立实现HTTP调用服务。

You can use either resources, or build services that implement http calls.

如果你想使用的资源,请记住:

If you want to use resources, remember:


  1. 要包括角resource.js文件,你可以在这里找到

  2. 要在您的模块声明,包括像ngResource模块依赖包括这样: angular.module('对myApp',['ngResource'])

  1. to include the angular-resource.js file which you can find here
  2. to include in your module declaration to include the ngResource module dependency like so: angular.module('myApp',['ngResource'])

这之后,你可以用这种方式宣告资源:

After that you can declare a resource in this fashion:

function MyController($scope, $resource){
  var User = $resource('/user/:userId', {userId:'@id'});
  var user = User.get({userId:123}, function() {
    user.abc = true;
    user.$save();
  });
}

此外,使用服务,如果你需要的粒度更深层次,如

Alternatively, use services if you need a much deeper level of granularity such as

angular.module('myApp')
.factory('MyAPIService', function($http){
  var apiurl, myData;
  return {
    getData: function(){
      $http.get(apiurl)
      .success(function(data, status, config, headers){
        myData = data;
      })
      .error(function(){ //handler errors here
      });
    },
    data: function() { return myData; }
  };
});

我觉得服务,因为共享控制器之间的数据的能力是巨大的,所以你可以像这样把他们注入在控制器

I find services to be great because of the ability to share data between controllers, so you can inject them in a controller like so

myapp.controller('MyController', function($scope, MyAPIService){
  $scope.data = MyAPIService.data();
  // etc.

});

这篇关于从angularjs调用REST API的最佳方式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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