我在 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/