i want to get just my service in the variable from my controller but it give me an $$state object
this is my controller
$scope.myDataSMS = ServiceSms.async().then(function(data){
$scope.myDataSMS1 = data;
console.log($scope.myDataSMS1);
return $scope.myDataSMS1;
});
console.log($scope.myDataSMS);
and my service
routeAppControllers.factory('ServiceSms', function($http,Token) {
var key = Token.CreateToken()
var myService = {
async: function() {
var data = 'token=' + encodeURIComponent(key);
var promise = $http({
method: 'POST',
url: 'PhpFunction/getsms.php',
data: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(data) {
// The then function here is an opportunity to modify the response
// console.log(data.data);
// The return value gets picked up by the then in the controller.
return data.data;
})
// Return the promise to the controller
return promise;
}
};
return myService;
});
i think that the problems is with the promise but there i m little bit stuck
if someone can help me please
thanks in advance
this would be a better way to write your promise:
CONTROLLER:
.controller('nameofcontroller', ['$scope', 'ServiceSms', function($scope, ServiceSms) {
$scope.myDataSMS = ServiceSms.async()
.then(
function(data){
$scope.myDataSMS1 = data;
console.log($scope.myDataSMS1);
return $scope.myDataSMS1;
},
function(err){
console.log('err: ' + err);
});
}]);
SERVICE:
routeAppControllers.factory('ServiceSms', function($http,Token) {
return {
async: function() {
var data = 'token=' + encodeURIComponent(key);
return $http({
method: 'POST',
url: 'PhpFunction/getsms.php',
data: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
}
}
});
Related
I am trying to pass an http response from my controller to a service, it works well except for getting the response to go into the controller here is my code below:
For my service
app.factory('ApiService',function($http,Config,$q){
return {
login: function(payload,callBack){
var deferred = $q.defer();
$http({
method:'POST',
url:Config.baseUrl + '/api/login',
data:payload,
headers: {'Content-Type': 'application/json'},
}).then(function successCallback(callBack){
console.log(callBack);
return deferred.resolve(callBack);
}, function errorCallback(callBack){
//deferred.reject(error);
console.log(callBack);
return deferred.reject(callBack);
});
return deferred.promise;
}
}
});
and for the Controller
app.controller('LoginCtrl', function($scope,$position,$rootScope,$state,ApiService) {
$scope.forms = {
'loginForm':''
}
var payload ={
'username':'',
'password':''
}
$scope.userLogin = function(form){
$scope.username = form.username.$modelValue;
$scope.password = form.password.$modelValue;
payload ={
"username":$scope.username,
"password":$scope.password
}
ApiService.login(payload, function(result){
console.log(result);
}
});
Now I don't understand because when I console.log() the response I'm able to see it in the service but doing the same on the controller I'm getting nothing.
No need to make it complex. Simply return promise from factory and use it in controller.
factory:
app.factory('ApiService',function($http,Config,$q) {
return {
login: function(payload) {
return $http({
method:'POST',
url:Config.baseUrl + '/api/login',
data:payload,
headers: {'Content-Type': 'application/json'},
});
}
}
});
in controller :
ApiService.login(payload).then(function(data){
// use response data
}, function(error) {
// handle error
});
You should use it like this:
ApiService.login(payload).then(function(result){
console.log(result);
});
Because you are returning a promise in your service.
Also you don't need that callback parameter, because the then method on the promise is your callback when it finishes and you can access the data your resolve it with.
app.factory('ApiService',function($http,Config,$q){
return {
login: function(payload){
var deferred = $q.defer();
$http({
method:'POST',
url:Config.baseUrl + '/api/login',
data:payload,
headers: {'Content-Type': 'application/json'},
}).then(function (result){
return deferred.resolve(result);
}, function (result){
return deferred.reject(result);
});
return deferred.promise;
}
}
});
I am trying to call a factory to generate token from two different controllers
1.homeCtrl
2.savingsCtrl
but m getting same token value in both places
here is my code
---factory
app.factory('tokenFactory', ['$http', function($http) {
return $http({
method: 'POST',
url: "../api/v1/getToken",
headers : {
'Content-Type':'application/json',
'X-API-KEY':'04g4g00c04ks4sokgkoosg0kwww0cww4www0kc80',
'Authorization':"Basic cGVzYXZlQXBwOkNDNTVzV0FwUW0zYWxpazlLNTcwTTFXQ1RNOUJ1TmZS"
},
data: {"grant_type":"client_credentials"}
}) .success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
----homeCtrl
app.controller('homeCtrl', ['$scope','tokenFactory', function($scope,tokenFactory){
tokenFactory.success(function(data) {
$scope.token = data;
var token=data.access_token;
}])
----savingsCtrl
app.controller('savingsCtrl', ['$scope','tokenFactory','savingsFactory', function($scope,tokenFactory,savingsFactory){
tokenFactory.success(function(data) {
$scope.token = data;
var token=data.access_token;
var userId='9c28735e-8a29-401d-b94e-6cc90a087d96';
alert(token)
$scope.getGoals=function(){
savingsFactory.getGoals(userId,token).success(function(data) {
$scope.goals = data;
var goal=$scope.goals.goalName;
alert(goal)
});
}
You should return the $http with some method not directly in factory
app.factory('tokenFactory', ['$http', function($http) {
var getToken = function(){
return $http({
method: 'POST',
url: "../api/v1/getToken",
headers : {
'Content-Type':'application/json',
'X-API-KEY':'04g4g00c04ks4sokgkoosg0kwww0cww4www0kc80',
'Authorization':"Basic cGVzYXZlQXBwOkNDNTVzV0FwUW0zYWxpazlLNTcwTTFXQ1RNOUJ1TmZS"
},
data: {"grant_type":"client_credentials"}
}) .success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}
return {
getToken : getToken
}
}]);
and then use it in controllers like this
tokenFactory.getToken().then(function (data) {
$scope.token = data.data.access_token;
var token = data.data.access_token;
alert(token);
});
I have tested this and its working
Try this:
----factory
app.factory('tokenFactory', ['$http', function($http) {
function getToken() {
$http({
method: 'POST',
url: "../api/v1/getToken",
headers : {
'Content-Type':'application/json',
'X-API-KEY':'04g4g00c04ks4sokgkoosg0kwww0cww4www0kc80',
'Authorization':"Basic cGVzYXZlQXBwOkNDNTVzV0FwUW0zYWxpazlLNTcwTTFXQ1RNOUJ1TmZS"
},
data: {"grant_type":"client_credentials"}
})
}
return {getToken: getToken}
}]);
----homeCtrl
app.controller('homeCtrl', ['$scope','tokenFactory', function($scope,tokenFactory){
tokenFactory.getToken()
.success(function(data) {
$scope.token = data;
var token=data.access_token;
}
}])
----savingsCtrl
app.controller('savingsCtrl', ['$scope','tokenFactory','savingsFactory', function($scope,tokenFactory,savingsFactory){
tokenFactory.getToken()
.success(function(data) {
$scope.token = data;
var token=data.access_token;
var userId='9c28735e-8a29-401d-b94e-6cc90a087d96';
alert(token)
$scope.getGoals=function(){
savingsFactory.getGoals(userId,token).success(function(data) {
$scope.goals = data;
var goal=$scope.goals.goalName;
alert(goal)
});
}
}])
Please note that I already read all the StackOverflow questions that are somewhat related to my questions but none of these really answer my question. Please don't mark this as duplicate without fully understanding my question.
Here's my concern:
I would like to delay angularJS $http.get call without affecting the angular promise. Right now the code below throws a "angular-1.3.15.js:11655 TypeError: Cannot read property 'then' of undefined" in this line:
updatedPromise = promise.then(function(price)
Here's my partial code:
MyAPP.service('FirstService', ['$q','$http', 'Constants', 'SecondService', 'UtilityService', function($q, $http, Constants, SecondService, UtilityService) {
var self = this;
var processFunction = function(AnArray) {
var updatedPromise;
var promises=[];
angular.forEach(AnArray, function(itemObj, index)
{
var totalWorth = "";
if(itemObj.name != "")
{
var promise = SecondService.getPrice(itemObj.name);
updatedPromise = promise.then(function(price){
itemObj.price = price;
return itemObj;
}, function(error){
console.log('[+] Retrieving price has an error: ', error);
});
promises.push(updatedPromise);
}
else
{
console.log("Error!");
}
});
return $q.all(promises);
};
);
MyAPP.service('SecondService', ['$timeout','$http', 'Constants', function($timeout, $http, Constants) {
var self = this;
var URL = "/getPrice";
self.getPrice = function(itemName){
$timeout(function(){
var promise;
promise = $http({
url: URL,
method: 'POST',
data: {_itemName : itemName},
headers: {'Content-Type': 'application/json'}
}).then(function(response) {
return response.data;
}, function(response) {
console.log("Response: " + response.data);
return response.data;
});
return promise;
}, 3500);
console.log("[-]getPrice");
};
}]);
Please note that the processFunction should really return an array of promises because this is needed in other functions.
Your help will be highly appreciated!
Let me know for further questions/clarifications.
Thanks!
$timeout returns a promise, so you can return that, and then return the promise from $http:
self.getPrice = function (itemName) {
return $timeout(3500).then(function () {
return $http({
url: URL,
method: 'POST',
data: { _itemName: itemName },
headers: { 'Content-Type': 'application/json' }
});
}).then(function (response) {
return response.data;
}, function (response) {
console.log("Response: " + response.data);
return response.data;
});
};
I have created a factory to run an $http GET method. I need to add an input value to the URL pulling in the JSON but I'm having trouble passing it from the controller. I can see that the URL is being created correctly, I am just missing the "query" parameter from the form input field.
Here is my HTML block:
<input type="string" class="form-control" ng-model="getMovie.title">
Here is my factory and controller:
var app = angular.module('app', []);
app.factory("getMovie", ['$http',function($http){
var obj = {};
var url = "https://api.nytimes.com/svc/movies/v2/reviews/search.json";
obj.getMovieInfo = function(){
return $http({
url: url,
method: "GET",
params:{
query: this.title, // This is the value I need
api_key: "68094e1974e7984c256beb1653319915:3:33678189",
callback: "JSON_CALLBACK"
},
headers: {
"Content-Type" : "application/json"
}
}).then(function successCallback(response) {
this.movieReviews = response.data.results;
}, function errorCallback(response) {
console.log("Nothing to see here...");
});
}
return obj;
}]);
app.controller('moviesCtrl', ["$scope", "getMovie", function($scope, getMovie){
$scope.findMovie = function(){
getMovie.getMovieInfo().then(function(response){
$scope.results = response;
});
}
}]);
Thanks!
You can send the title as parameter to the factory method.
<input type="string" class="form-control" ng-model="title">
var app = angular.module('app', []);
app.factory("getMovie", ['$http',function($http){
var obj = {};
var url = "https://api.nytimes.com/svc/movies/v2/reviews/search.json";
obj.getMovieInfo = function(title){
return $http({
url: url,
method: "GET",
params:{
query: title, // This is the value I need
api_key: "68094e1974e7984c256beb1653319915:3:33678189",
callback: "JSON_CALLBACK"
},
headers: {
"Content-Type" : "application/json"
}
}).then(function successCallback(response) {
this.movieReviews = response.data.results;
}, function errorCallback(response) {
console.log("Nothing to see here...");
});
}
return obj;
}]);
app.controller('moviesCtrl', ["$scope", "getMovie", function($scope, getMovie){
$scope.findMovie = function() {
getMovie.getMovieInfo($scope.title).then(function(response){
$scope.results = response;
});
}
}]);
I recommend you dont use this . If you want use controllerAs syntax , use like this . You can see more in here
https://github.com/johnpapa/angular-styleguide/tree/master/a1#controllers
app.factory("getMovie", ['$http',function($http){
var vm = this
vm.getMovie ={};
And in ajax
return $http({
url: url,
method: "GET",
params:{
query: vm.getMovie, // This is the value I need
api_key: "68094e1974e7984c256beb1653319915:3:33678189",
callback: "JSON_CALLBACK"
},
headers: {
"Content-Type" : "application/json"
}
}).then(function successCallback(response) {
vm.movieReviews = response.data.results;
}, function errorCallback(response) {
console.log("Nothing to see here...");
});
}
return obj;
}]);
I am stuck here, I don't know what I am missing or how to debug this further. I continue to get this error: 'updateMemberServiceFactory is undefined' when I call it from an ng-click event. Please advise. If this is a simple typo I apologize I just can't see what's wrong. I'm trying to call into a PUT method on my controller but it never gets called. New to AngularJS. Thank you.
securityApp.factory('updateMemberServiceFactory', function ($http) {
function update(memberServiceID) {
$http({ method: 'PUT', url: 'http://localhost:62791/api/MemberServices/', data: { memberServiceID: memberServiceID } })
.then(function (result) {
alert('success');
}, function (errorResponse) {
});
};
});
securityApp.controller('memberServicesController', function ($scope, $http, $routeParams, $location, getTokenFromServer, updateMemberServiceFactory) {
var id = $routeParams.memberID;
$scope.username = 'aharris1#test.com';
$scope.password = 'SuperPass1!';
getTokenFromServer.getToken($scope.username, $scope.password).then(function (data) {
$scope.token = data;
$http({ method: 'GET', url: '/api/MemberServices/' + id + '?access_token=' + $scope.token, headers: { 'Authorization': 'Bearer ' + $scope.token } })
.success(function (response) {
$scope.memberServices = "";
$scope.memberServices = response;
$http({ method: 'GET', url: '/api/Members/' + id + '?access_token=' + $scope.token, headers: { 'Authorization': 'Bearer ' + $scope.token } })
.success(function (response) {
$scope.member = response;
});
$http.get('/api/ServiceTypes/')
.then(function (response) {
$scope.serviceTypes = response.data;
});
});
});
$scope.updateMemberService = function () {
updateMemberServiceFactory.update( { memberServiceID: memberServiceID }, null, function () {
alert('update called');
});
};
});
<i class="fa fa-save"></i>
When you use someApp.factory(someFunction) the some someFunction should return an object that will be injected when needed.
In your case:
securityApp.factory('updateMemberServiceFactory', function ($http) {
function update(memberServiceID) {
$http({ method: 'PUT', url: 'http://localhost:62791/api/MemberServices/', data: { memberServiceID: memberServiceID } })
.then(function (result) {
alert('success');
}, function (errorResponse) {
});
};
return { // <---- this object will get injected, when required
update : update
}
});