我一生都没有做过angularJS,我迷失了。
所以我已经完成了这个文件,用过滤时间从api获取数据。
forecast.js
(function() {
angular.module('application').factory('Forecast', ['$http', '$q', function($http, $q){
var ApiAddr = "api.com/";
forecast.getResults = function(timeStart, timeEnd){
// We map application varaible names with API param names
var httpParams = {
type: "global",
time: "minute",
tsmin: timeStart,
tsmax: timeEnd
};
return $http.get(apiAddr, {
params: httpParams,
cache: true
}).then(function(data){
return data;
},
function(response){
console.log(
"HTTP request "+ApiAddr+
" (with parameters tsmin="+httpParams.tsmin+", tsmax="+httpParams.tsmax+
", type="+httpParams.type+", time="+httpParams.time+
(httpParams.motive ? ", motive="+httpParams.motive : "")+
(httpParams.vector ? ", vector="+httpParams.vector : "")+
(httpParams.media ? ", media="+httpParams.media : "")+
") failed with "+response.status
);
return $q.reject(response);
}
);
}];
但我不知道为此制作一个控制器适配器。我能做什么类型的控制器? 每个例子都基于一个固定的json文件,没有参数。
此外,我希望在HTML中加入时间过滤器,但我完全不知道该怎么做。我见过的例子是获取数据,不发送。
Ps:我对此进行了2天的研究,我从未做过前端编程。
答案 0 :(得分:1)
TextViewWithInsets
(function() {
angular.module('application', [])
.factory('Forecast', ['$http', '$q', function($http, $q) {
var apiaddress = 'api.com';
var forecast = {};
forecast.getResults = function(timeStart, timeEnd) {
// We map application varaible names with API param names
var httpParams = {
type: "global",
time: "minute",
tsmin: timeStart,
tsmax: timeEnd
};
return $http.get(apiaddress, {
params: httpParams,
cache: true
}).then(function(result) {
return result.data;
});
};
return forecast;
}])
.controller('SampleCtrl', ['$scope', 'Forecast', function($scope, Forecast) {
$scope.forecastReport = '';
$scope.getForecast = function() {
Forecast.getResults($scope.timeStart, $scope.timeEnd)
.then(function(report) {
$scope.result = report;
}).catch(function(err) {
$scope.result = '';
console.error('Unable to fetch forecast report: ' + err);
});
};
}]);
})();
答案 1 :(得分:0)
将工厂注入您的控制器,如下所示:
var app = angular.module('application');
app.controller('myController',
['$scope', 'Forecast', function($scope, Forecast) { /* access to Forecast*/}]);
或使用组件(清洁工):
app.component('myComponentCtrl', {
templateUrl: 'template.html'
controller: myComponentCtrl
})
myComponentCtrl.$inject = ['$scope', 'Forecast'];
function myComponentCtrl($scope, Forecast) {/* ... */ }