What I want to do is to use the ui-router resolution angular install-bar.
How can I run the codes given in Resolve?
resolve: {
return {
loadedData: function($rootScope, $q) {
var deferred = $q.defer();
$rootScope.$on('cfpLoadingBar:completed', function() {
console.log("complete");
deferred.resolve();
});
return deferred.promise;
}
};
}
In terms of being an example;
greeting: function($q, $timeout){
var deferred = $q.defer();
$timeout(function() {
deferred.resolve('Hello!');
}, 1000);
return deferred.promise;
}
Instead of
I want to run this code, it works every timeout.
Rootscope.on works only when the page is loaded.
greeting: function($q, $rootScope){
var deferred = $q.defer();
$rootScope.$on('cfpLoadingBar:completed', function(){
deferred.resolve('Hello!');
});
return deferred.promise;
}
Related
I would like to test $resource success and error callbacks in my controller. I don’t want to use $httpBackend as that would be used to test the data service. It seems that there is no way to do it though - the only solution I have found is to use promises instead which I could either resolve or reject. Does this sound right? Anyway, here is what I have at the moment - currently it only tests whether the $resource get() is called:
The controller:
angular
.module('myModule')
.controller('MyCtrl', MyCtrl);
MyCtrl.$inject = [
'dataService'
];
function MyCtrl(
dataService
) {
var vm = this;
vm.getData = getData;
function getData() {
dataService.getData().get(function(response) {
// stuff to test
},
function(error) {
// stuff to test
});
}
The test:
describe('Controller: MyCtrl', function() {
var MyCtrl;
var rootScope;
var scope;
var dataServiceMock = {
getData: jasmine.createSpy('getData')
};
beforeEach(function()
inject(function($controller, $rootScope) {
rootScope = $rootScope;
scope = $rootScope.$new();
MyCtrl = $controller('MyCtrl as vm', {
dataService: dataServiceMock,
});
});
});
describe('vm.getData()', function() {
beforeEach(function() {
dataServiceMock.getData.and.returnValue({
get: jasmine.createSpy('get')
});
});
it('gets the data', function() {
scope.vm.getData();
expect(dataServiceMock.getData().get).toHaveBeenCalled();
});
});
});
Try this
function getData (query) {
var deferred = $q.defer();
var httpPromise = $resource(query,{},{
post:{
method:"GET",
isArray: false,
responseType: "json"
}
});
httpPromise.post({}, {},
function(data) {
try {
var results = {}
results.totalItems = data.response;
deferred.resolve(results);
} catch (error) {
console.log(error.stack);
deferred.reject();
}
},
function(error) {
deferred.reject();
}
);
return deferred.promise;
}
I am first time using angular JS so kindly bear my question. While creating service in angular JS I have to write var deferred = $q.defer(); and then return deferred.promise; in every method of service which use $http()
Is there any shorthand or alternative way to do so?
for eg:
(function() {
'use strict';
angular
.module('app')
.service('AuthService', function($q, $http, $interval, $timeout, BASE_URL) {
var service = {
login: function(formdata) {
var deferred = $q.defer();
$http.post(BASE_URL + '/api/getLogin', formdata).then(function(response) {
deferred.resolve(response);
}, function(err) {
deferred.reject(err);
});
return deferred.promise;
},
signup: function(formdata) {
var deferred = $q.defer();
$http.post(BASE_URL + '/api/register', formdata).then(function(response) {
deferred.resolve(response);
}, function(err) {
deferred.reject(err);
});
return deferred.promise;
},
forgot: function(formdata) {
var deferred = $q.defer();
$http.post(BASE_URL + '/api/forgot', formdata).then(function(response) {
deferred.resolve(response);
}, function(err) {
deferred.reject(err);
});
return deferred.promise;
}
}
return service;
});
here you can see I have to rewrite the same line of code in every method of service
use $http methods without any other code:
return $http.post(BASE_URL + '/api/getLogin', formdata)
all $http methods return promise by default
I have two factories in my angular app.
app.factory('FavoritesArtists',['$http', '$q', 'UserService', function($http, $q, UserService){
var deferred = $q.defer();
var userId = UserService.getUser().userID;
$http.get('http://myurl.com/something/'+userId)
.success(function(data) {
deferred.resolve(data);
})
.error(function(err) {
deferred.reject(err);
});
return deferred.promise;
}]);
And I have a value I get from another factory :
var userId = UserService.getUser().userID;
But I doesn't update when the UserService.getUser() is changed, the view changes with $watch, but I don't know how it work inside a factory.
Any help is welcome, thanks guys !
Anyone ?
app.factory('FavoritesArtists',['$http', '$q', 'UserService', function($http, $q, UserService){
var deferred = $q.defer();
$http.get('https://homechefhome.fr/rise/favorites-artists.php?user_id='+userId)
.success(function(data) {
deferred.resolve(data);
})
.error(function(err) {
deferred.reject(err);
});
return deferred.promise;
}]);
I simply need to make userId variable dynamic..
A better design pattern will be this
app.factory('UserService',
['$http', function($http) {
var getUser = function() {
return http.get("url_to_get_user");
};
return {
getUser: getUser
};
}]);
app.factory('ArtistService',
['$http', '$q', 'UserService', function($http, $q, UserService) {
var getFavoriteArtists = function() {
UserService.getUser().then(function(response) {
var userId = response.data.userID;
return $http.get('http://myurl.com/something/' + userId);
}, function() {
//passing a promise for error too
return $q.reject("Error fetching user");
});
};
return {
getFavoriteArtists: getFavoriteArtists
};
}]);
Now call it in controller like,
ArtistService.getFavoriteArtists().then(function(response) {
//do something with response.data
}, function(response) {
//log error and alert the end user
});
I have array of promises.
var defered = q.defer();
// promises is a array which will have different promises
var promises = [];
q.all(promises).then(function(response){
// SUSSECCFULLY RESOLVED ALL PROMISE THEN EXECUTION COME HERE
}, function(error){
// IF ANY PROMISE FAILED THEN EXECUTION COME HERE
});
I want to process all promises whether they fail or they resolved.
Use case 1:
You want to handle errors to be handled separately and success on all not called:
var myApp = angular.module('myApp', []);
function MyCtrl($scope, $q, $timeout) {
function prOne(){
var d = $q.defer();
setTimeout(function(){
d.reject();
}, 100);
return d.promise;
}
function prTwo(){
var d = $q.defer();
setTimeout(function(){
d.resolve();
}, 100);
return d.promise;
}
$q.all([prOne().catch(function(){ console.log('fail for one'); return $q.reject() }), prTwo()]).then(function(){
console.log('success');
return $q.resolve();
}).catch(function(){
console.log('error');
});;
}
myApp.controller('MyCtrl', MyCtrl);
Use case 2:
You want to handle errors to be handled separately and success on all called anyway:
var myApp = angular.module('myApp', []);
function MyCtrl($scope, $q, $timeout) {
function prOne(){
var d = $q.defer();
setTimeout(function(){
d.reject();
}, 100);
return d.promise;
}
function prTwo(){
var d = $q.defer();
setTimeout(function(){
d.resolve();
}, 100);
return d.promise;
}
$q.all([prOne().catch(function(){ console.log('fail for one'); return $q.resolve() }), prTwo()]).then(function(){
console.log('success');
return $q.resolve();
}).catch(function(){
console.log('error');
});;
}
myApp.controller('MyCtrl', MyCtrl);
I am new to AngularJS and having an strange problem, that I can't access to $scope.name. In the factory DataService I have a method getData() which uses $http.get(...).
angular.module("app", []).factory("DataService", function($q, $http) {
var service = {};
service.getData = function() {
var deferred = $q.defer();
$http.get(apiPath).success(function(data) {
deferred.resolve(data);
}).error(function(data, status) {
deferred.reject('Error: ' + status);
});
return deferred.promise;
};
return service;
}).controller("DataController", ["$scope", "DataService", function($scope, DataService) {
$scope.datas = [];
DataService.getData().then(function(data){
$scope.datas = data;
}, function(error) {
console.log(error);
});
console.log($scope.datas); // it returns []
}]);
I can't understand why it returns an empty array.