我是AngularJS的新手,我正在尝试使用它向远程服务器发送http get请求,而不会影响任何现有的视图代码。我找到了一种在html准备好后立即运行函数的方法,使用独立的init()。然而,当我像一样编码时
var init= function($http, $location) {
//using $location to fetch query string
if ($location.search().hasOwnProperty('a') && $location.search().hasOwnProperty('b')){
var a= $location.search().a;
var b= $location.search().b;
var sendurl = 'http://someurl'+a+b ;
var req = {
method:'GET',
url: sendurl,
headers:{
'Content-Type': 'text/html'
},
data: {token: ''}
};
$http(req)
.success( function(){
alert('success!');
})
.error(function(){
alert("ERROR");
});
}
};
init() ;
在控制台中,错误为TypeError: $location is undefined
。我知道这一定是我不知道如何在一个独立的函数中使用AngularJS代码,所以我想问如何编写这样的函数。
尝试在服务中编写这样的函数。
var myApp = angular.module('myApp', []);
myApp.factory('SomeService', function ($http, $location) {
return {
init: init
};
function init () {
if ($location.search().hasOwnProperty('a') && $location.search().hasOwnProperty('b')){
var a= $location.search().a;
var b= $location.search().b;
var sendurl = 'http://someurl'+a+b ;
var req = {
method:'GET',
url: sendurl,
headers:{
'Content-Type': 'text/html'
},
data: {token: ''}
};
$http(req)
.success( function(){
alert('success!');
})
.error(function(){
alert("ERROR");
});
}
}
});
并且在向控制器调用init函数之后
myApp.controller('MyController', function (SomeService){
SomeService.init();
});