When I get the data from the service using getAllGenres everything works fine, but when I try to pass the parameter vm.id the data is of type undefined. Please help. P.S. from an Angular new comer
genresService:
angular.module('movies.services', [])
.factory('genresService', ['$http', function ($http) {
function callback () {
// TODO: Implement callback function
}
function getAllGenres (callback) {
var url = '/api/genres';
$http.get(url)
.success(function (data) {
callback(data);
})
.error(function (error) {
console.log(error);
})
}
function getGenreById (id) {
var url = '/api/genres/' + id;
console.log(id);
$http.get(url)
.success(function (data) {
callback(data);
})
.error(function (error) {
console.log(error);
})
}
return {
getAllGenres: getAllGenres,
getGenreById: getGenreById
};
}]);
GenresController:
.controller('GenresController', ['$scope', 'genresService',
function ($scope, genresService) {
var vm = this;
genresService.getAllGenres(function (data) {
vm.genres = data;
});
}])
GenresDetailsController:
.controller('GenreDetailsController', ['$routeParams', 'genresService',
function ($routeParams, genresService) {
var vm = this;
vm.id = $routeParams.id;
genresService.getGenreById(vm.id, function (data) {
console.log(data);
})
}]);
Related
Upgrade to angularjs version 1.7 and this code does not compile
app.factory('LoginService', function ($http) {
return {
login: function (param, callback) {
$http.post(url, param)
.success(callback)
.error(function (data, status, headers, config) {
});
}
};
});
On the controller I make the call to the service LoginService
function LoginController($http, $location, LoginService, blockUI) {
var vm = this;
LoginService.usuario(
{login: vm.username, clave: vm.password},
function (data, status, headers, config) {
vm.resultado = data;
if (vm.resultado == "True") {
window.location = "/Home/Index";
} else {
vm.error = 'Usuario o password incorrecto';
}
});
};
I want to know how the function is called from the controller because it implemented the http.post service using .then
app.factory('LoginService', function ($http) {
return {
login: function (data) {
$http.post(url, data)
.then(function (resultado) {
debugger;
if (resultado.data === "True") {
return resultado.data;}
else {
console.log("NO");}
});
}};
});
I suggest you get familiar with a AngularJS $q service and its Promise API.
You LoginService.login(...) method should return the Promise from $http.post(...):
app.factory('LoginService', function ($http) {
return {
login: function (data) {
return $http.post(url, data)
.then(function(response) {
return response.data;
});
});
Then, your Controller can access the returned data via the resolved Promise:
function LoginController(LoginService) {
var vm = this;
LoginService.login({login: vm.username, clave: vm.password})
.then(function (result) {
// handle result here...
});
the solution would be this:
function LoginController($scope,$window,$q,LoginService) {
$scope.fnBusqueda = function () {
var promesas = [
obtenerLogin()
];
$q.all(promesas).then(function (promesasRes) {
var oArrayResponse = promesasRes;
if ((oArrayResponse.length > 0)) {
$scope.respuesta = oArrayResponse[0];
if ($scope.respuesta == "True") {
window.location = "/Home/Index";
} else {
$cope.error = 'Usuario o password incorrecto';
}
}
});
};
function obtenerLogin() {
var defered = $q.defer();
var promise = defered.promise;
LoginService.login(url_valida_login, '{login:X,clave:X}').then(function (response) {
defered.resolve(response);
}).catch(function (data) {
defered.resolve([]);
})
return promise;
}
}
I have made a service and I am getting the data but it does not return any thing to controller.
My service. js file
app.factory('countryService', function ($http) {
return {
getCountries: function () {
$http.get('http://abc/countries')
.success(function (data) {
console.log(data);
})
.error(function (data) {
console.log(data);
});
}
};
});
and here is my controller
$scope.countries = function () {
$scope.countries_data = countryService.getCountries();
console.log($scope.countries_data);
};
What is my mistake ?
You might need to do some structural changes like following
app.factory('countryService', function ($http) {
return {
getCountries: function () {
return $http.get('http://abc/countries'); //just return promise
}
};
});
Let service return the promise, Do other proceedings inside the controller,Define success callback and faiure callback for the same
$scope.countries = function () {
$scope.countries_data = countryService.getCountries().then(success, failure); // callbaks
};
function success(response){
console.log(response); // logs the results
}
function failure(response){
console.log(response); // logs the errors if any
}
Hope this will help
In your service:
app.factory('countryService', function ($http) {
return {
getCountries: function () {
return $http.get('http://abc/countries') // add return this service
.success(function (data) {
console.log(data);
})
.error(function (data) {
console.log(data);
});
}
};
});
In controller:
$scope.countries = function () {
countryService.getCountries().then(function(res){
$scope.countries_data = res;
console.log($scope.countries_data);
});
};
I have a factory which fetches data from server and passes to controllers , many controllers are calling get methods from the factory , but only the scope variable of controller that calls the factory first is changed in view not all... here is my factory code
(function () {
angular.module('myapp').factory('agendaFactory', ['$http', '$q', function ($http, $q) {
var user = "";
var defer = $q.defer();
var agenda = {
getAll: function (tempData, addType) {
$http.post('/api/' + addType + '/getAll', tempData).success(function (data, status) {
console.log(addType, data);
//console.log(status);
defer.resolve(data);
}).error(function (err, status) {
console.log(err, status);
defer.reject(status);
});
return defer.promise;
}
};
return agenda;
}]);
}());
here are the two controllers calling them..
changeData = function (data) {
console.log("called function in liffe");
$scope.lifetimeData = data;
}
agendaFactory.getAll(tempData, addType).then(function (data) {
console.log('lifeData', data);
changeData(data);
return;
}, function (err) {
console.log('today err', err);
})
and second controller
changeData = function (data) {
console.log("called function in year");
$scope.yearData = data;
}
agendaFactory.getAll(tempData, addType).then(function (data) {
console.log('yeardata', data);
changeData(data);
return;
}, function (err) {
console.log('today err', err);
});
but data from only first controller is being updated in the view
Remove the promise wrapper since $http already returns a promise. Also get rid of the success/error handlers since they're deprecated.
(function () {
angular.module('myapp').factory('agendaFactory', ['$http', '$q', function ($http, $q) {
var user = "";
var agenda = {
getAll: function (tempData, addType) {
return $http.post('/api/' + addType + '/getAll', tempData);
}
};
return agenda;
}]);
}());
You can then handle the success/error conditions in your controller
I have a factory, calling the service and getting the response and passing in to the controller and trying to store the response in a variable which is getting undefined
app.factory('Myservice', function (service1, service2) {
return {
getService: function (data) {
service1("user", encodeURIComponent("pass")).then(function (response) {
varSessionData = response.Obj;
var queryString = strURL[1].split("&");
Service2.pageLoad(SessionData).then(function (response) {
var homeScreen = response;
data(homeScreen);
});
});
}
};
});
In Controller:
var Mydata = MyService.geService(function (data) {
Console.log(data);
return data; // getting response
});
$scope.Hello = Mydata; // undefined
Whenever you make any AJAX request they are asynchronous. That is why Angular promises are used (the .then method). So you should change your code like this in your controller:
MyService.geService(function (data) {
Console.log(data);
$scope.Hello = data;
});
Change it to the following, your data isn't defined synchronously.
Controller:
MyService.geService(function(data) {
$scope.Hello = data;
});
i have pass the $scope.Hello in Another Service controller,which means depend upon that taking the result from services.
Not working?
var HomeController = function ($scope, $rootScope, $http, $stateParams, $state, Service3, Myservice)
{
MyService.geService(function (data) {
Console.log(data);
$scope.Hello = data;
});
Not working
Service3.pageLoad($scope.Hello) // not get the value
.then(function (response) {
$scope.ServiceModelobj = response;
console.log(response);
}
Working code
var HomeController = function ($scope, $rootScope, $http, $stateParams, $state, Service3, Myservice)
{
MyService.geService(function (data) {
Console.log(data);
$scope.Hello = data;
Working//
Service3.pageLoad($scope.Hello) // get the value
.then(function (response) {
$scope.ServiceModelobj = response;
console.log(response);
});
}
}
In my app.config i need to retrieve a value from a service but i have an error message : UserServiceProvider.getUser is not a function. The goal is to allow the user to access some pages only if he is a part of a list.
Here's my service code :
var app = angular.module('myApp');
app.service('UserService', '$http', '$q', function(){
userService.getUser = function () {
var deferred = $q.defer();
return $http.get(userUrl + "getUserName")
.success(function (data) {
deferred.resolve(userService.userName = data);
console.log(data);
//alert('Success loading user');
}).error(function (error) {
deferred.reject(error);
//alert('Error loading user' + error.message);
})
return deferred.promise;
}
return userService;
});
My config :
app.config(function(UserServiceProvider){
UserServiceProvider.getUser()
.then(function (data) {
console.log(UserServiceProvider.userName);
});
});