AngularJs Resolve Response of a Promise (UI.Router + $http.get) - angularjs

apothekenService.getApotheke returns a promise. response.data within the promise is a json object which is delivered correctly, I can see that in the first console.log.
How can I get this json object to my variable in the resolve? When I do the same in a controller I just use $scope and bind the variable within the response but in this case I don't have a scope.
angular.module("test", ["ngAnimate", "ngCookies", "ngTouch", "ngSanitize", "ngResource", "ui.router", "ui.bootstrap", "ui.bootstrap.showErrors", "myApothekenService"]).config(function($stateProvider, $urlRouterProvider, $uiViewScrollProvider, showErrorsConfigProvider) {
$uiViewScrollProvider.useAnchorScroll;
return $stateProvider.state("root", {
abstract: true,
controller: "RootCtrl",
resolve: {
Apotheke: function(apothekenService) {
this.apo = {};
apothekenService.getApotheke().then(function(response) {
console.log(response.data);
return this.apo = response.data;
});
console.log(this.apo);
return this.apo;
}
}
});
}).controller("RootCtrl", function($scope, $location, $anchorScroll, Apotheke) {
$scope.apotheke = Apotheke;
console.log($scope.apotheke);
});

You know this inside the promise resolve function (then) is different than the this inside the parent resolve function. If you want to use this pattern, the usual convention is to capture this in a local variable self, and use that throughout your resolve function.
But anyways, I will just do as below. This way, the controller code won't execute until the resolve promise is resolved.
Apotheke: function(apothekenService) {
return apothekenService.getApotheke();
}**

Related

$state are not populated in resolving promises in Angular routes

I came across this situation where I can see $stateParams gets populated in one place but not in another. I'm kind of newbie to angular-ui-router so any help will be appreciated.Thanks !
In the resolve block of the following state, I injected $stateParams as a dependency in the function for data 'campaign' and the $stateParams is populated.
.state('campaign', {
url: "/campaign/{campaignId:int}",
templateUrl: campaign_template,
controller: 'CampaignCtrl',
parent: 'org',
abstract: true,
resolve: {
campaign: function(CampaignService, $stateParams) {
console.log('$stateParams is populated here!', $stateParams)
return CampaignService.get($stateParams.campaignId)
.then(function(campaign) {
return campaign;
});
}
}
Inside the CampaignService function, however, I require $stateParams but it's
empty. I'm confused because I'm assuming since it's populated when I injected it in the
resolve block, it should be the same no matter where else I get it again.
.service('CampaignService', function($injector, $q) {
this.get = function() {
var $stateParams = $injector.get('$stateParams');
console.log('$stateParams is empty here!', $stateParams);
var deferred = $q.defer();
setTimeout(function() {
deferred.resolve({
name: 'campaignName'
});
}, 1000);
return deferred.promise;
}
})
I'm assuming since it's populated when I injected it in the resolve block, it should be the same no matter where else I get it again.
The $stateParams injected into the resolve block is the proposed future state. At that point in time the application is still using the old state. And will remain in the old state if any of the resolve promises are rejected.
Under the hood, the $state service creates a local version of $stateParams that it injects in the resolve function:
var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params.$$keys(), params);
var locals = { $stateParams: $stateParams };
// Resolve 'global' dependencies for the state, i.e. those not specific to a view.
// We're also including $stateParams in this; that way the parameters are restricted
// to the set that should be visible to the state, and are independent of when we update
// the global $state and $stateParams values.
dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state);
var promises = [dst.resolve.then(function (globals) {
dst.globals = globals;
})];
— https://github.com/angular-ui/ui-router/blob/legacy/src/state.js#L1427-L1437
The solution is to pass the proposed future $stateParams to the service.
Your service probably shouldn't care about state parameters. You are already passing in the campaignId value inside of your state definition so in order to consume that within the service you could modify it like this:
.service('CampaignService', function($injector, $q) {
this.get = function(campaignId) {
console.log('campaignId = ' + campaignId);
var deferred = $q.defer();
setTimeout(function() {
deferred.resolve({
name: 'campaignName'
});
}, 1000);
return deferred.promise;
}
})

'invocables' must be an object

I have a state as following :
.state('core.recover', {
url: '/recover',
controller: 'RecoverPasswordCtrl',
templateUrl: 'views/tmpl/recoverAccount/recover-password.html'
})
I want when I enter to this state to check something before loading the template, in this case I want to call an api that checks for something if the promise is successful it will continue and display the template, otherwise it will redirect the user to another state.
I tried to do this on the top of the controller but I always see the template for a moment then it redirects me, so I tried to use resolve as in this post :
AngularJS | handle routing before they load
As following :
.state('core.recover', {
url: '/recover',
controller: 'RecoverPasswordCtrl',
resolve: function(recoverAccountService, $location, $state, $q) {
var deferred = $q.defer();
deferred.resolve();
recoverAccountService.get({email:$location.search().email, verificationKey:$location.search().verificationKey})
.$promise.then(function (result) {}).catch(function (err) {
$state.go("candidature.pre");
});
return deferred.promise;
},
templateUrl: 'views/tmpl/recoverAccount/recover-password.html'
})
but it didn't work and I'm getting this error in the browser's console :
Error: 'invocables' must be an object
How can I solve this ?
You're not using the correct syntax, uiRouter is expecting as entry for resolve an object, which keys it will try to evaluate.
Lets abbreviate your resolving function as aimadResolver, such that
var aimadResolver = function(recoverAccountService, $location, $state, $q) {
var deferred = $q.defer();
deferred.resolve();
recoverAccountService.get({ email: $location.search().email, verificationKey: $location.search().verificationKey })
.$promise.then(function(result) {}).catch(function(err) {
$state.go("candidature.pre");
});
return deferred.promise;
}
Of course, this is not mandatory, but I'm doing it for the sake of readability. Then, your state definition should be as follows:
state('core.recover', {
url: '/recover',
controller: 'RecoverPasswordCtrl',
resolve: {'yourResolverName': aimaidResolver}
},
templateUrl: 'views/tmpl/recoverAccount/recover-password.html'
})
Don't forget to inject yourResolverName in RecoverPasswordCtrl, or else your controller will be instantiated without waiting anyway. Source: look for the resolve examples
On the side
I'd like to point out that your use of deferred objects doesn't make sense. You're immediately resolving your deferred object on the second line within your function, which means that recoverAccountservice.get() could still be pending while RecoverPasswordCtrl is already being instantiated. Assuming that recoverAccountservice.get() returns a promise (and if it doesn't, you should change it such that it does), you can more efficiently write:
var aimadResolver = function(recoverAccountService, $location, $state, $q) {
return recoverAccountService.get({... })
.then(function(result) {
// do nothing? Apparently you only want to $state.go on a rejection of the promise
})
.catch(function(err) {
$state.go("candidature.pre");
return $q.when()
})
}
More on the use of $q.when() versus deferred can be found here.

Execute code within a factory when needed, not when loaded into controller

Factory:
.factory("myFac", ['$http', '$q', function($http, $q) {
var defer = $q.defer();
$http.get('some/sample/url').then(function (response) { //success
/*
* Do something with response that needs to be complete before
* controller code is executed.
*/
defer.resolve('done');
}, function() { //error
defer.reject();
});
return defer.promise;
}]);
Controller:
.controller("testCtrl", ['$scope', 'myFac', function($scope, myFac) {
/*
* Factory code above is executed immediately as 'myFac' is loaded into controller.
* I do not want this.
*/
if($scope.someArbitraryBool === true) {
//THIS is when I want to execute code within myFac
myFac.then(function () {
//Execute code that is dependent on myFac resolving
});
}
}]);
Please let me know if it is possible to delay the code in the factory until I need it. Also, if there's a better way to execute on this concept, feel free to correct.
You factory has $http.get directly inside factory function which return custom $q promise. So while you inject the factory dependency inside your controller function, it ask angular to create an object of myFac factory function, while creating object of function it executes the code block which you have returned your factory, basically which returns promise.
What you could do is, just return a object {} from the factory function which will have method name with its definition, so when you inject inside angular controller it will return service object, which will various method like getData method. And whenever you want to call the method of factory you could do factoryName.methodName() like myFac.getData().
Also you have created a extra promise inside your service which is not needed in first place, as you can utilize the promise of $http.get (which returns a promise object.)
Factory
.factory("myFac", ['$http', function($http) {
var getData = return $http.get('some/sample/url').then(function (response) { //success
return 'done'; //return to resolve promise with data.
}, function(error) { //error
return 'error'; //return to reject promise with data.
});
return {
getData: getData
};
}]);
Controller
.controller("testCtrl", ['$scope', 'myFac', function($scope, myFac) {
if($scope.someArbitraryBool === true) {
//Here you could call the get data method.
myFac.getData().then(function () {
//Execute code that is dependent on myFac resolving
});
}
}]);

How get access to global variable from Factory Angular JS?

I tried to write factory method in Angular JS:
.factory('FriendsFactory', function(){
var friend = {};
friend.delete = function(id) {
notificationsModal.show('danger', messages_info[86]);
notificationsModal.confirm(function() {
this.deleteAjax(event, id, type);
})
}
friend.deleteAjax = function (event, id, type){
var target = angular.element(event.target);
var request = $http({
method: "POST",
url: "/subscribe/deletesubscriber",
data: $.param({ id : id, type : type }),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
request.success(function () {
target.closest('.notif-item').remove();
$scope.counter--;
});
request.error(function () {
// TODO
});
}
return friend;
})
This code has two methods: friend.delete() also friend.deleteAjax()
Calling functions from Factory:
.controller('FriendsController', ['$scope','$http', 'friendsFactory', function($scope, $http) {
$scope.deleteUser = function (idUser) {
friendsFactory.delete(idUser);
}
}])
I need decrement variable $scope.counter in friend.deleteAjax() ajax response, regardless controller from was called factory.
I can do duplicate in each controller:
$scope.counter = 10; and after call factory, but it is not good
Although the answer suggested by #JBNizet is absolutely correct but if you are bound to use the code in the way it is, then you can do two things. First is to simply pass the $scope from controller to service call (which is not a cleaner approach is not recommended):
$scope.deleteUser = function (idUser) {
friendsFactory.delete(idUser, $scope);
}
And you can use the scope inside the factory.
The second option to use current controller's scope to root scope and then use this in the factory.
In your controller
$scope.deleteUser = function (idUser) {
$rootScope.callingControllerScope = $scope;
friendsFactory.delete(idUser);
}
In your factory
friend.deleteAjax = function (event, id, type){
console.log($rootScope.callingControllerScope.counter);
// your code
}
And you also need to fix your dependency injection:
.controller('FriendsController', ['$scope','$http', 'FriendsFactory', function($scope, $http, friendsFactory) {
$scope.deleteUser = function (idUser) {
friendsFactory.delete(idUser, $scope);
}
}]);
You're doing many, many things wrong:
Using friendsFactoryinstead of FriendsFactory:
.controller('FriendsController', ['$scope','$http', 'friendsFactory'
here --------^
Forgetting to declare friendsFactory as an argument of the controller function:
.controller('FriendsController', ['$scope','$http', 'friendsFactory', function($scope, $http) {
here ----^
Accessing an undefined $scope variable in the service:
$scope.counter--;
^--- here
Doing DOM manipulation in a service...
The service responsibility is not to manipulate the DOM and the controller scope.
The DOM should be modified using directives in the html template.
The controller scope should be managed by the controller, not by the service. Return the promise request from the deleteAjax() function, and let the controller register a success callback, rather than doing it in the service. This callback will then be able to access the controller scope.
Note that most errors are basic JavaScript error that should be signalled by a good JavaScript editor, or at least by looking at errors in the console of your browser.

Inject service in app.config

I want to inject a service into app.config, so that data can be retrieved before the controller is called. I tried it like this:
Service:
app.service('dbService', function() {
return {
getData: function($q, $http) {
var defer = $q.defer();
$http.get('db.php/score/getData').success(function(data) {
defer.resolve(data);
});
return defer.promise;
}
};
});
Config:
app.config(function ($routeProvider, dbService) {
$routeProvider
.when('/',
{
templateUrl: "partials/editor.html",
controller: "AppCtrl",
resolve: {
data: dbService.getData(),
}
})
});
But I get this error:
Error: Unknown provider: dbService from EditorApp
How to correct setup and inject this service?
Set up your service as a custom AngularJS Provider
Despite what the Accepted answer says, you actually CAN do what you were intending to do, but you need to set it up as a configurable provider, so that it's available as a service during the configuration phase.. First, change your Service to a provider as shown below. The key difference here is that after setting the value of defer, you set the defer.promise property to the promise object returned by $http.get:
Provider Service: (provider: service recipe)
app.provider('dbService', function dbServiceProvider() {
//the provider recipe for services require you specify a $get function
this.$get= ['dbhost',function dbServiceFactory(dbhost){
// return the factory as a provider
// that is available during the configuration phase
return new DbService(dbhost);
}]
});
function DbService(dbhost){
var status;
this.setUrl = function(url){
dbhost = url;
}
this.getData = function($http) {
return $http.get(dbhost+'db.php/score/getData')
.success(function(data){
// handle any special stuff here, I would suggest the following:
status = 'ok';
status.data = data;
})
.error(function(message){
status = 'error';
status.message = message;
})
.then(function(){
// now we return an object with data or information about error
// for special handling inside your application configuration
return status;
})
}
}
Now, you have a configurable custom Provider, you just need to inject it. Key difference here being the missing "Provider on your injectable".
config:
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: "partials/editor.html",
controller: "AppCtrl",
resolve: {
dbData: function(DbService, $http) {
/*
*dbServiceProvider returns a dbService instance to your app whenever
* needed, and this instance is setup internally with a promise,
* so you don't need to worry about $q and all that
*/
return DbService('http://dbhost.com').getData();
}
}
})
});
use resolved data in your appCtrl
app.controller('appCtrl',function(dbData, DbService){
$scope.dbData = dbData;
// You can also create and use another instance of the dbService here...
// to do whatever you programmed it to do, by adding functions inside the
// constructor DbService(), the following assumes you added
// a rmUser(userObj) function in the factory
$scope.removeDbUser = function(user){
DbService.rmUser(user);
}
})
Possible Alternatives
The following alternative is a similar approach, but allows definition to occur within the .config, encapsulating the service to within the specific module in the context of your app. Choose the method that right for you. Also see below for notes on a 3rd alternative and helpful links to help you get the hang of all these things
app.config(function($routeProvider, $provide) {
$provide.service('dbService',function(){})
//set up your service inside the module's config.
$routeProvider
.when('/', {
templateUrl: "partials/editor.html",
controller: "AppCtrl",
resolve: {
data:
}
})
});
A few helpful Resources
John Lindquist has an excellent 5 minute explanation and demonstration of this at egghead.io, and it's one of the free lessons! I basically modified his demonstration by making it $http specific in the context of this request
View the AngularJS Developer guide on Providers
There is also an excellent explanation about factory/service/provider at clevertech.biz.
The provider gives you a bit more configuration over the .service method, which makes it better as an application level provider, but you could also encapsulate this within the config object itself by injecting $provide into config like so:
Alex provided the correct reason for not being able to do what you're trying to do, so +1. But you are encountering this issue because you're not quite using resolves how they're designed.
resolve takes either the string of a service or a function returning a value to be injected. Since you're doing the latter, you need to pass in an actual function:
resolve: {
data: function (dbService) {
return dbService.getData();
}
}
When the framework goes to resolve data, it will inject the dbService into the function so you can freely use it. You don't need to inject into the config block at all to accomplish this.
Bon appetit!
Short answer: you can't. AngularJS won't allow you to inject services into the config because it can't be sure they have been loaded correctly.
See this question and answer:
AngularJS dependency injection of value inside of module.config
A module is a collection of configuration and run blocks which get
applied to the application during the bootstrap process. In its
simplest form the module consist of collection of two kinds of blocks:
Configuration blocks - get executed during the provider registrations and configuration phase. Only providers and constants
can be injected into configuration blocks. This is to prevent
accidental instantiation of services before they have been fully
configured.
I don't think you're supposed to be able to do this, but I have successfully injected a service into a config block. (AngularJS v1.0.7)
angular.module('dogmaService', [])
.factory('dogmaCacheBuster', [
function() {
return function(path) {
return path + '?_=' + Date.now();
};
}
]);
angular.module('touch', [
'dogmaForm',
'dogmaValidate',
'dogmaPresentation',
'dogmaController',
'dogmaService',
])
.config([
'$routeProvider',
'dogmaCacheBusterProvider',
function($routeProvider, cacheBuster) {
var bust = cacheBuster.$get[0]();
$routeProvider
.when('/', {
templateUrl: bust('touch/customer'),
controller: 'CustomerCtrl'
})
.when('/screen2', {
templateUrl: bust('touch/screen2'),
controller: 'Screen2Ctrl'
})
.otherwise({
redirectTo: bust('/')
});
}
]);
angular.module('dogmaController', [])
.controller('CustomerCtrl', [
'$scope',
'$http',
'$location',
'dogmaCacheBuster',
function($scope, $http, $location, cacheBuster) {
$scope.submit = function() {
$.ajax({
url: cacheBuster('/customers'), //server script to process data
type: 'POST',
//Ajax events
// Form data
data: formData,
//Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false,
success: function() {
$location
.path('/screen2');
$scope.$$phase || $scope.$apply();
}
});
};
}
]);
You can use $inject service to inject a service in you config
app.config(function($provide){
$provide.decorator("$exceptionHandler", function($delegate, $injector){
return function(exception, cause){
var $rootScope = $injector.get("$rootScope");
$rootScope.addError({message:"Exception", reason:exception});
$delegate(exception, cause);
};
});
});
Source: http://odetocode.com/blogs/scott/archive/2014/04/21/better-error-handling-in-angularjs.aspx
** Explicitly request services from other modules using angular.injector **
Just to elaborate on kim3er's answer, you can provide services, factories, etc without changing them to providers, as long as they are included in other modules...
However, I'm not sure if the *Provider (which is made internally by angular after it processes a service, or factory) will always be available (it may depend on what else loaded first), as angular lazily loads modules.
Note that if you want to re-inject the values that they should be treated as constants.
Here's a more explicit, and probably more reliable way to do it + a working plunker
var base = angular.module('myAppBaseModule', [])
base.factory('Foo', function() {
console.log("Foo");
var Foo = function(name) { this.name = name; };
Foo.prototype.hello = function() {
return "Hello from factory instance " + this.name;
}
return Foo;
})
base.service('serviceFoo', function() {
this.hello = function() {
return "Service says hello";
}
return this;
});
var app = angular.module('appModule', []);
app.config(function($provide) {
var base = angular.injector(['myAppBaseModule']);
$provide.constant('Foo', base.get('Foo'));
$provide.constant('serviceFoo', base.get('serviceFoo'));
});
app.controller('appCtrl', function($scope, Foo, serviceFoo) {
$scope.appHello = (new Foo("app")).hello();
$scope.serviceHello = serviceFoo.hello();
});
Using $injector to call service methods in config
I had a similar issue and resolved it by using the $injector service as shown above. I tried injecting the service directly but ended up with a circular dependency on $http. The service displays a modal with the error and I am using ui-bootstrap modal which also has a dependency on $https.
$httpProvider.interceptors.push(function($injector) {
return {
"responseError": function(response) {
console.log("Error Response status: " + response.status);
if (response.status === 0) {
var myService= $injector.get("myService");
myService.showError("An unexpected error occurred. Please refresh the page.")
}
}
}
A solution very easy to do it
Note : it's only for an asynchrone call, because service isn't initialized on config execution.
You can use run() method. Example :
Your service is called "MyService"
You want to use it for an asynchrone execution on a provider "MyProvider"
Your code :
(function () { //To isolate code TO NEVER HAVE A GLOBAL VARIABLE!
//Store your service into an internal variable
//It's an internal variable because you have wrapped this code with a (function () { --- })();
var theServiceToInject = null;
//Declare your application
var myApp = angular.module("MyApplication", []);
//Set configuration
myApp.config(['MyProvider', function (MyProvider) {
MyProvider.callMyMethod(function () {
theServiceToInject.methodOnService();
});
}]);
//When application is initialized inject your service
myApp.run(['MyService', function (MyService) {
theServiceToInject = MyService;
}]);
});
Well, I struggled a little with this one, but I actually did it.
I don't know if the answers are outdated because of some change in angular, but you can do it this way:
This is your service:
.factory('beerRetrievalService', function ($http, $q, $log) {
return {
getRandomBeer: function() {
var deferred = $q.defer();
var beer = {};
$http.post('beer-detail', {})
.then(function(response) {
beer.beerDetail = response.data;
},
function(err) {
$log.error('Error getting random beer', err);
deferred.reject({});
});
return deferred.promise;
}
};
});
And this is the config
.when('/beer-detail', {
templateUrl : '/beer-detail',
controller : 'productDetailController',
resolve: {
beer: function(beerRetrievalService) {
return beerRetrievalService.getRandomBeer();
}
}
})
Easiest way:
$injector = angular.element(document.body).injector()
Then use that to run invoke() or get()

Resources