Azz*_*ude 9 javascript angularjs angularjs-service angular-http
我已经在angular中定义了一个自定义http服务,如下所示:
angular.module('myApp')
.factory('myhttpserv', function ($http) {
var url = "http://my.ip.address/"
var http = {
async: function (webService) {
var promise = $http.get(url + webService, { cache: true }).then(function (response) {
return response.data;
});
return promise;
}
};
return http;
});
Run Code Online (Sandbox Code Playgroud)
我可以在我的控制器中访问此服务,如下所示:
angular.module('myApp')
.controller('myCtrl', function (myhttpserv) {
var webService = 'getUser?u=3'
myhttpserv.async(webService).then(function (data) {
console.log(data);
})
});
Run Code Online (Sandbox Code Playgroud)
但是,我现在需要简化此过程,以便使用静态URL将其全部包含在服务中,并且它只返回数据.所以我可以在控制器中调用它,如下所示:
angular.module('myApp')
.controller('myCtrl', function ($scope, myhttpserv) {
console.log(myhttpserv.var1);
console.log(myhttpserv.var2);
etc...
});
Run Code Online (Sandbox Code Playgroud)
我似乎无法调整服务以获得此功能.有人知道正确的方法吗?
Rob*_*zvi 16
选项1 - 使用promise API
angular.module('myApp').factory('myhttpserv', function ($http) {
return $http.get('http://my.ip.address/getUser?u=3', { cache: true });
});
Run Code Online (Sandbox Code Playgroud)
控制器:
angular.module('myApp').controller('myCtrl', function ($scope, myhttpserv) {
myhttpserv.then(function(response){
console.log(response.data);
});
});
Run Code Online (Sandbox Code Playgroud)
选项2 - 使用路由解析
angular.module('myApp', ['ngRoute']).config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/myCtrl', {
templateUrl: 'myView.html',
controller: 'myCtrl',
resolve: {
load: function (myhttpserv) {
return myhttpserv;
}
});
}]);
Run Code Online (Sandbox Code Playgroud)
服务:
angular.module('myApp').factory('myhttpserv', function ($http) {
var data = {};
var url = "http://my.ip.address/";
var promise = $http.get(url + 'getUser?u=3', { cache: true }).then(function (response) {
data = response.data;
});
return data;
});
Run Code Online (Sandbox Code Playgroud)
控制器:
angular.module('myApp')
.controller('myCtrl', function ($scope, myhttpserv) {
console.log(myhttpserv.data.var1);
console.log(myhttpserv.data.var1);
etc...
});
Run Code Online (Sandbox Code Playgroud)
选项3 - 使用$ interval服务
angular.module('myApp').factory('myhttpserv', function ($http) {
var data = {};
var url = "http://my.ip.address/";
var promise = $http.get(url + 'getUser?u=3', { cache: true }).then(function (response) {
data = response.data;
});
return data;
});
Run Code Online (Sandbox Code Playgroud)
控制器:
angular.module('myApp').controller('myCtrl', function ($scope, $interval, myhttpserv) {
$scope.intervalPromise = $interval(function(){
if (Object.keys(myhttpserv.data).length!=0)
{
console.log(myhttpserv.data);
$interval.cancel($scope.intervalPromise);
}
}, 100);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19226 次 |
| 最近记录: |