javascript - 在 AngularJS 中为 $http 联系 REST API 设置服务或工厂的最佳实践

标签 javascript angularjs rest service controller

我在 AnguarJS 服务中创建了 $http 和 REST API 接口(interface)作为一个函数,可以像这样注入(inject)到不同的 Controller 中:

// Global service to share between states
.service("appSharedService", ['$http', function($http) {
  // Method: Returns list of all cities.
  this.restCitiesGet = function() {
     return $http.get('http://example/nkhorasaniec7/api/v0/city');
  };

  // Method:
  this.citiesGet = function() {
    this.restCitiesGet().success(function (data) {
        console.log(data);
        return data;
      })
  };
}])

控制台日志(数据);当我调用 citiesGet() 时返回正确的 json 输出。

// Main controller that prints list of cities.
.controller('CityList', ['$scope', function($scope, appSharedService) {
  $scope.cities = appSharedService.citiesGet();
  console.log($scope.cities);
}]);

这是我的 Controller 注入(inject)我的服务。控制台日志($scope.cities);这里返回未定义。

$scope.cities 值在路由调用此 Controller 后不会改变。

我的设置有问题吗?

有趣的是,在我改变路线并再次回到这个 Controller 之后,这次 $scope.cities 有我的 REST 数据,一切都很好。

我认为这里存在我不知道的计时或异步功能问题。

编辑:

我本可以在我的 Controller 中使用 $http 并且一切正常:

.controller('CityList', ['$scope', '$http', function($scope, $http, appSharedService) {
  $http.get('http://localhost/nkhorasaniec7/api/v0/city').success(function (data) {
        $scope.cities = data;
      });
}]);

但我想为此实现辅助函数。

最佳答案

我想说的是,常见的方法是将 promise 直接返回给 Controller ,就像您上面提到的直接使用 http 请求一样。

// Global service to share between states
.service("appSharedService", ['$http', function($http) {


// Method: Returning the promise
this.citiesGet = function() {
  return $http.get('http://example/nkhorasaniec7/api/v0/city');

 };
}])

Controller :

  .controller('CityList', ['$scope', '$http', function($scope, $http, appSharedService) {
appSharedService.citiesGet().success(function (data) {
      $scope.cities = data;
    });
 }]);

关于javascript - 在 AngularJS 中为 $http 联系 REST API 设置服务或工厂的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23757861/

相关文章:

Php 插入后错误访问被拒绝用户 'root' @'localhost'(使用密码 : YES)

javascript - javascript 中 throttle 的函数式编程等价物是什么?

mysql - auth0 身份验证和自定义数据库不起作用

javascript - angularjs - 表单 ng-submit 不适用于动态生成的表单 html

java - REST Web服务jpa更新语句

java - 为什么我的 Java 项目无法成功执行 POST 方法来连接我的 OrientDB?

javascript - 如何使用 AES-GCM C#.NET 加密() 然后 JS WebCryptoApi 解密()?

javascript - 理解 SetTimeout 命令

javascript - 从 Javascript 中的回调函数返回

angularjs - 选中复选框 ng-change 第一次不会触发