我有2个服务,我想将变量发送到一个并获得返回。我该怎么做?
这是我的代码
var services = angular.module('service', []);
services.factory('startApp',['$http','kickTheTires',
function($http,kickTheTires){
kickTheTires('this is my var');
}]);
services.factory('kickTheTires',[function(val){
console.log(val)
}]);
提前谢谢你!
答案 0 :(得分:0)
希望这有帮助,
services.factory('startApp',['$http', function($http){
return {
getMyVariable : function() {
return $http.get('myservice/abc');
}
};
}]);
services.factory('kickTheTires',['$http', function($http){
return {
getTheTires : function(myvar) {
return $http.get('myservice/xyz?' + myvar );
}
}
}]);
startApp.getMyVariable().then(function(result) {
return kickTheTires.getTheTires(result);
})
.then(function(result) {
console.log(result);
});
答案 1 :(得分:0)
服务可以与控制器服务相同的方式进行通信。 请看这里的演示
http://jsbin.com/kudoli/1/edit?console,output
var app = angular.module('app',[]);
app.controller('fCtrl', function($scope,queryService){
queryService.setquery("my day");
queryService.getData();
});
app.factory('queryService', function(dataService){
function setquery(q){
dataService.query.q = q;
}
function getData(){
dataService.getData().then(function(){
console.log("--------------");
console.log("service a");
console.log(dataService.data.info);
});
}
return {
setquery : setquery,
getData:getData
};
});
app.factory('dataService', function($http, $q, filterFilter) {
var API = "https://ws.spotify.com/search/1/track.json";
var query = {
q: "",
page: 0
};
var data ={
tracks: [], info : {}
};
var getData = function() {
var deferred = $q.defer();
console.log("--------------");
console.log("service b");
console.log("Call api");
console.log(query);
$http({
method: 'get',
url: API,
params: query
}).then(onSucess, onError);
function onSucess(response) {
angular.copy(response.data.tracks, data.tracks);
angular.copy(response.data.info, data.info);
deferred.resolve();
}
function onError() {
alert("Can't get data");
deferred.reject();
}
return deferred.promise;
};
return {
data: data,
query: query,
getData:getData
};
});