【发布时间】:2016-08-01 13:29:36
【问题描述】:
我对 AngularJS 还很陌生,并且刚刚开始掌握许多我特别喜欢 MVC 设计模式的概念。但是我很难在我的应用程序中实现服务层。
我发现,在我的控制器调用服务中的方法后,它会在服务返回数据之前继续执行代码;这样当服务返回数据时,它对控制器没有任何用处。
为了更好地说明我的意思,下面是代码:
var InsightApp = angular.module('InsightApp', ['chart.js']);
// Module declaration with factory containing the service
InsightApp.factory("DataService", function ($http) {
return {
GetChartSelections: function () {
return $http.get('Home/GetSalesData')
.then(function (result) {
return result.data;
});
}
};
});
InsightApp.controller("ChartSelectionController", GetAvailableCharts);
// 2nd Controller calls the Service
InsightApp.controller("DataController", function($scope, $http, DataService){
var response = DataService.GetChartSelections();
// This method is executed before the service returns the data
function workWithData(response){
// Do Something with Data
}
}
我发现的所有示例似乎都按照我在这里的方式构建或略有不同;所以我不确定我应该做些什么来确保异步执行。
在 Javascript 世界中,我会将服务移至 Controller 内部,以确保它异步执行;但我不知道如何在 Angular 中实现这一点。此外,无论如何,这样做与角度注入是反直觉的。
那么正确的做法是什么?
【问题讨论】:
-
人人都说回报承诺! Angular 2 合并了 RxJS(反应式扩展)。 Angular 1 你必须自己做,但想法是一样的。这是你必须学习的
Observer=>Observable模式。
标签: javascript angularjs model-view-controller