Passing a parameter to async service method from controller - angularjs

I am new to angularjs so I am struggling to pass a parameter to service method from controller.
My controller looks like this:
userControllers.controller('StartController', function(startService,$scope) {
var server='http://localhost:8080/terminal/1';
// Call the async method and then do stuff with what is returned inside our own then function
startService.async().then(function(d) {
$scope.message = d;
});
});
Service method:
myService.factory('startService', function($http) {
var startService = {
async: function () {
// $http returns a promise, which has a then function, which also returns a promise
var promise = $http.get('http://localhost:8080/terminal/1').then(function (response) {
// The then function here is an opportunity to modify the response
console.log(response.headers('link'));
// The return value gets picked up by the then in the controller.
return response;
});
// Return the promise to the controller
return promise;
}
};
return startService;
});
And this code works fine. Now I want to pass variable 'server' from controller to be used in service instead of link. Any idea how to do that? How to use more than one variable in service function call?

Updated code is in between ** **
userControllers.controller('StartController', function(startService,$scope) {
var server='http://localhost:8080/terminal/1';
// Call the async method and then do stuff with what is returned inside our own then function
**startService.async(server).then(function(d) {**
$scope.message = d;
});
});
myService.factory('startService', function($http) {
var startService = {
async: **function (server) {**
// $http returns a promise, which has a then function, which also returns a promise
var promise = **$http.get(server)**.then(function (response) {
// The then function here is an opportunity to modify the response
console.log(response.headers('link'));
// The return value gets picked up by the then in the controller.
return response;
});
// Return the promise to the controller
return promise;
}
};
return startService;
});

Related

Create angular promise with another value

I have a web service which returns some data. To prevent code duplication I want to move http request call to angular service:
angular.module('abc', [])
.factory('def', function () {
return {
getData: function () {
return $http.post('/path/', {});
}
};
});
All is good, but necessary data is inside complicated object, and I have to write every time:
def.getData().then(function (response) {
scope.obj = response.data.qwe.rty.xyz;
});
What is the easiest way to return promise, which will send value of response.data.qwe.rty.xyz directly to successCallback? And I can write like this:
def.getData().then(function (obj) {
scope.obj = obj;
});
The call $http.post('/path/', {}) returns a promise on which you then call then(). Note that then() also returns a promise, so you can chain the calls. Your code could therefore look like this:
angular.module('abc', [])
.factory('def', function () {
return {
getData: function () {
return $http.post('/path/', {})
.then(function(response) {
return response.data.qwe.rty.xyz;
});
}
};
});
you can use the deferring behavior that implemented in the $q provider
like so :
angular.module('abc', [])
.factory('def', function ($q) {
return {
getData: function () {
var def = $q.defer
$http.post('/path/', {}).then(function(response){
def.resolve(response.data.qwe.rty.xyz)
});
return def.promise;
}
};
});
and use it in your controller like :
def.getData().then(function (response) {
scope.obj = response;
});

delay response in JSON data which is local machine in angular js

In my angular application
there is function init();
which I called in starting to may javascript
then there is getMonthlyNews function which is called after init()
function init() {
configService.getResponders().then(function (data) {
apiUrl = data;
});
}
which is getting some setting from JSON file in local js/ folder
(function(){
app.factory("configService", ['$http', function ($http) {
return {
getResponders: function () {
return $http.get('assets/js/service/config.json')
.then(function (res) {
console.log("Data " + res.data.url);
return res.data.url;
});
}
};
}]);
})();
json file
{
"url":"http://localhost:6790//api/getNews/"
}
function getMonthlyNews() {
var method = 'Search'
var url = apiUrl + method;
}
after calling init function in js file I need to get apiUrl form json file which is on local js folder using service
to get that value I have to call
when I call init function it takes time and return value after some time later
but that time interval my function getMonthlyNews already executed with an undefined error so that I have to add a setTimeOut function like that
setTimeout(function () { getMonthlyNews(); }, 200);
so how to deal with this delay or any other idea
You are treating a promise wrongly. All code that assumes that the promise finishes should be in it's then function.
var promise;
function init() {
promise = configService.getResponders().then(function (data) {
apiUrl = data;
});
}
...
function getMonthlyNews() {
promise.then(function() {
var method = 'Search'
var url = apiUrl + method;
})
}
getting url should be done by using the new promise.

Angularjs factory http return value

i've this factory thar call external api that return an array:
angular.module('starter.services', [])
.factory('PlacesService', function($http) {
var places = "";
var request = $http({
method: "get",
url: 'http://someurl/getPlaces.php'
});
request.then(function (data) {
places = data.response
});
console.log(places); // return empty string
return {
all: function() {
return places;
},
get: function(placesId) {
return places[placesId];
}
}
});
Places variable returned by http is an empty string.
If I initialize places as an array and the I use places.push(data.response) it works, but return an array of array.
Could you help me?
Your log here is outside of the context of the promise the $http call is returning. Basically the log gets executed before the promise is resolved, so your string is still empty when the log executes.

Wait till success or error occur

I'm trying use $http.get() in a factory to retrieve a value which will be processed further in a controller.
appFac.factory('CompletedJobs',function($http){
var result;
return{
getJobs : function(webserviceurl){
$http.get(webserviceurl).success(function(data){
result = data;
})
.error(function(err){
result = '';
});
return result;
}
}
})
appCtrl.controller('Ctrl',function(CompletedJobs){
var data = CompletedJobs.getJobs('some url');
// some other logic based on data
});
Due to the asynchronism, by the time the data becomes available inside the factory method, it is of no use to the controller because the factory method has already returned undefined.
Can anyone help me work out how to get the data from the factory method so it can be used by the controller?
In your factory you should return the promise of success or error instead of explicitly returning the result because that will be returned before your promise get resolved. Modify you factory like this.
appFac.factory('CompletedJobs',function($http, $q){
return{
getJobs : function(webserviceurl){
var deferred = $q.defer();
$http.get(webserviceurl).then(function(response){
deferred.resolve(response.data);
return deferred.promise;
});
}
}
})
appCtrl.controller('Ctrl',function(CompletedJobs){
var data = CompletedJobs.getJobs('some url');
// some other logic based on data
});
This should work for you.
In the factory return the promise.
appFac.factory('CompletedJobs',function($http){
return {
getJobs : function(webserviceurl){
//return the promise
return $http.get(webserviceurl);
}
};
In the controller chain from the promise.
appCtrl.controller('Ctrl',function(CompletedJobs){
var promise = CompletedJobs.getJobs('some url');
promise.then( function onFulfilled(result) {
var data = result.data
// some other logic based on data
}).catch( function onRejection(result) {
console.log(result.status);
});
});

Angular js service returns function objects when called from a controller?

var newservices = angular.module('newservices', []);
newservices.service('newservice', function ($http) {
return{
newdata: function(parameter){
return $http.get('/devicedetails/'+parameter).success(function(data) {
console.log(data)
return data
});
},
}
});
The above service is included in one of my controllers
data=newService.newdata($scope.dummy)
console.log(data)
while trying to print data what i get is $http function object as shown below
Object {then: function, catch: function, finally: function, success: function, error: function}
why is this so??
What you see is not an error. It's a Promise.
You did an $http GET request, which is asynchronous. $http.getreturns a promise that will be resolved when the remote request is completed. In that moment, you'll get the final value.
See this example, where getShops would be your method newData
this.getShop = function (id, lang) {
var promise = $http.get(appRoot + 'model/shops_' + lang + '.json');
return promise;
};
In a controller you can use it like this:
Shops.getShop($routeParams.id).then(function (response) {
console.log("data is", response.data);
$scope.shop = response.data[$routeParams.id];
});
When the data is ready, assign it to a scope.
In your case:
var data;
newService.newdata($scope.dummy).then(function (response) {
data = response.data;
});
Your service is returnig a promise
You should use some what like this, not tested though it should work.
data = newService.newdata($scope.dummy).then(function (response) {
return response.data;
},
function (error) {
return error;
});
You are using it wrong.
This work in promises. so in you controller you need to consume the promisses.
newService.newData($scope.dummy)
.then(function (data){
$scope.data = data;
console.log(data);
});
Try this.

Resources