access variables declared outside $q resolve function, inside the resolve function - javascript

I have a function(uploadOne) inside fileUpload service that uses $q and returns a promise:
function uploadOne(some input)
{
var deferred = $q.defer();
if (everything is OK) deferred.resolve(some Data);
else deferred.reject(some error);
return deferred.promise;
}
I inject fileUpload service and call uploadOne function inside my controller:
.controller('myController', ['$scope', 'lessonsService', 'fileUpload',
function ($scope, lessonsService, fileUpload) {
//outside variable
$scope.lessonData = {};
fileUpload.uploadOne(some input data).then(function (some response data) {
console.log($scope.lessonData); //is undefined
lessonsService; //is undefined
}, function (err) {
//some code here
});
}])
The problem is that the variable declared outside the success function ($scope.lessonData) is undefined. In addition, I cannot even use my other service (lessonsService) there since it is also undefined! I've seen the same behavior in other posts but none of them help. What mistake am I making?
As you noticed the code above is a simplified version of my real code.
Here is my real code. I'm using ng-file-upload to upload a photo in my mongoDB database. When the image is stored in the database, the id of the image is returned from the server:
.controller('UserPanelPostsController', ['$scope', 'lessonsService', 'fileUpload',
function ($scope, lessonsService, fileUpload) {
//outside variable
$scope.lessonData = {};
$scope.submitLesson = function () {
fileUpload.uploadOne($scope.file).then(function (imgData) {
imgData; //is OK
console.log($scope.lessonData); //is undefined
lessonsService; //is also undefined
}, function (err) {
//some code here
});
};
}])
Here is my service:
.service('fileUpload', ['$resource', '$http', 'baseURL', 'Upload', '$q',
function ($resource, $http, baseURL, Upload, $q) {
var deferred = $q.defer();
this.uploadOne = function (file) {
Upload.upload({
url: baseURL + 'pictures',
data: {file: file}
}).then(function (resp) {
deferred.resolve(resp.data);
}, function (resp) {
deferred.reject(resp.status);
}, function (evt) {
//some code here
});
return deferred.promise;
};
}])

Related

Unable to cancel request with $resource

After trying some solutions like this: Aborting ngResource using a promise object I'm unable to cancel a request made with $resource.
My last try was with this:
Controller:
angular.module('theApp')
.controller('homeController', function ($q, foodTypeFactory) {
var vm = this;
vm.testButton = function () {
vm.aborter = $q.defer();
foodTypeFactory(vm.aborter).getTest({}, function (data) {
console.log(data);
});
};
vm.cancelButton = function () {
vm.aborter.resolve();
}
});
foodTypeFactory:
angular.module('theApp')
.factory('foodTypeFactory', function ($resource, BACKEND_API) {
return function (aborter) {
return $resource(BACKEND_API + '/api/foodtypes/:id', {id: '#id'}, {
getTest: {
timeout: aborter.promise
}
});
}
});
Once the request is made it completes even if I try to cancel it.
I'm using Angular 1.6.2 with angular-resource 1.6.2.
What am I doing wrong?
What i Can suggest to you is to use an http interceptor .. the you can stop a request... somthing like this:
1) create a file like (auth.interceptor.js:
"use strict";
angular
.module("demo")
.factory('authInterceptorService', ['$q', '$location', 'localStorageService',
function ($q, $location, localStorageService) {
// Public Method
return {
request: function (config) {
config.headers = config.headers || {};
if(!MYCONDITION){ //<-- you can here your logic to test if conitnue request flow or not
return; //<-- TERMINATE IT ..
}else{
return config; //<-- CONTINUE WITH NORMAL REQUEST
}
}
};
}]);
2) in your app.config.js file:
$httpProvider.interceptors.push("authInterceptorService");
Then in ALL your request (via $http or via $resource) this logic is apply ... here you can also put the injection of the Bearer Token if you need it
Hope it help you
Finally I found a solution!
From angular 1.5 $resource can be cancelled with $cancelRequest().
In my case:
Controller:
angular.module('theApp')
.controller('homeController', function (foodTypeFactory) {
var vm = this;
vm.testButton = function () {
vm.onGoingRequest = foodTypeFactory.getTest({}, function (data) {
console.log(data);
});
};
vm.cancelButton = function () {
vm.onGoingRequest.$cancelRequest();
}
});
foodTypeFactory:
angular.module('theApp')
.factory('foodTypeFactory', function ($resource, BACKEND_API) {
return $resource(BACKEND_API + '/api/foodtypes/:id', {id: '#id'}, {
getTest: {
cancellable: true
}
});
});

Modify $scope from a Factory/Service in AngularJS

Can someone crate an example of how I could set a $scope variable from a outside the controller using a factory or service that uses AJAX?
Every time I have tried the AJAX variable returns undefined because the request has not returned yet, so $scope.var is undefined. After the AJAX request returns, $scope.var is still undefined even if I call the service from the Controller. Please help.
Please see demo here http://plnkr.co/edit/JcRY8uHRYaHH33UTH7Bt?p=preview
var app = angular.module("myapp", []);
app.service("dataService", function($http, $q) {
var data = [];
function getData() {
var deffered = $q.defer();
var request = {
url: 'data.json',
method: 'GET'
};
$http(request).then(sucess, error);
function sucess(response) {
deffered.resolve(response.data);
}
function error() {
deffered.reject();
}
return deffered.promise;
}
return {
data: data,
getData: getData
}
})
app.controller('MyControl', function($scope, dataService) {
$scope.data = [];
dataService.getData().then(function(response) {
$scope.data = response;
})
});

angular.identity is undefined

I'm trying to use the following...
.withHttpConfig({transformRequest: angular.identity})
but i always get undefined is not a function It does not seems to know what angular.identity is. Can anyone help?
full code:
angular.module('app.controllers.project', [
"app.factories.storage",
"app.factories.http",
"app.directives.typeahead",
"app.directives.projectDisplay",
"toaster"
])
.controller("projectController", ['$scope', '$rootScope', "$location",
"httpFactory", "filterService", "$stateParams", "toaster",
function ($scope, $rootScope, $location, httpFactory, filterService, $stateParams, toaster) {
var createProject = function () {
var resource = httpFactory
.withHttpConfig({transformRequest: angular.identity})
.post("project", data, {}, {'Content-Type': undefined})
.then(function () {
// do on success
console.log("done")
}, function () {
// do on failure
console.log("error")
});
etc
angular.identiy is a very simple function which just returns its arguments.
Here is the source code of it: https://github.com/angular/angular.js/blob/master/src/Angular.js#L379
What happens if you change your code from
.withHttpConfig({transformRequest: angular.identity})
to
.withHttpConfig({transformRequest: function(arg) { return arg; } })

Angular JS Method GET inside RUN after CONFIG

I need to do a request inside the RUN method to retrieve de user data from an api.
The first page (home), depends on the user data.
This is the sequence of dispatchs in my console:
CONFIG
RUN
INIT GET USER DATA
SIDEBAR
HOME
SUCCESS GET USER DATA
My problem is, i need to wait user data before call sidebar and home (controller and view) and i don't know how can i do this.
UPDATE
I have this until now:
MY CONFIG:
extranet.config(['$httpProvider', '$routeProvider', function ($httpProvider, $routeProvider) {
// My ROUTE CONFIG
console.log('CONFIG');
}]);
My RUN:
extranet.run(function($rootScope, $location, $http, Cookie, Auth, Session) {
console.log('RUN');
var token = Cookie.get('token');
// The login is done
var success = function (data) {
Session.create(data);
console.log('USER DATA SUCCESS');
};
var error = function () {
$location.path('/login');
};
// GET USER DATA
Auth.isAuthenticated().success(success).error(error);
});
MY CONTROLLER MAIN:
extranet.controller('MainCtrl', function ($scope, $location) {
console.log('MAIN CONTROLLER');
});
By using resolver
extranet.config(['$httpProvider', '$routeProvider', function ($httpProvider, $routeProvider) {
// My ROUTE CONFIG
$routeProvider.when('/', {
templateUrl: "/app/templates/sidebar.html",
controller: "siderbarController",
title: "EventList",
resolve: {
events: function ($q, Cookie,Session) {
var deffered = $q.defer();
Cookie.get('token').$promise
.then(function (events) {
Session.create(data);
console.log('USER DATA SUCCESS');
deffered.resolve(events);
}, function (status) {
deffered.reject(status);
});
return deffered.promise;
}
}
}]);
I hope you get some idea.
If you are using AngularJS methods for server requests you will get a promise. A promise gets resolved as soon as the response is recieved. All defined callbacks "wait" until the resolve.
Naive solution
So, you will use $http or even $resource if you have a REST-like backend:
var promise = $http.get(userDataUrl, params)
$rootScope.userDataPromise = promise;
After that you can use that promise whereever you need the data:
$rootScope.userDataPromise.then(myCallback)
Better solution
Using $rootScope for that purpose is not an elegant solution though. You should encapsulate the Userdata stuff in a service and inject it whereever you need it.
app.factory('UserData', ['$http',
function($http) {
var fetch = function() {
return $http.get(userDataUrl, params)
};
return {
fetch: fetch
};
}
]);
Now you can use that service in other modules:
app.controller('MainCtrl', ['$scope', 'UserService',
function ($scope, UserService) {
var update = function(response) {
$scope.userData = response.userData;
}
var promise = UserService.fetch();
promise.then(update)
}
);

Angular controller promises and testing

Im writing some unit tests for my controller which uses promises.
Basically this:
UserService.getUser($routeParams.contactId).then(function (data) {
$scope.$apply(function () {
$scope.contacts = data;
});
});
I have mocked my UserService. This is my unit test:
beforeEach(inject(function ($rootScope, $controller, $q, $routeParams) {
$routeParams.contactId = contactId;
window.localStorage.clear();
UserService = {
getUser: function () {
def = $q.defer();
return def.promise;
}
};
spyOn(UserService, 'getUser').andCallThrough();
scope = $rootScope.$new();
ctrl = $controller('ContactDetailController', {
$scope: scope,
UserService:UserService
});
}));
it('should return 1 contact', function () {
expect(scope.contacts).not.toBeDefined();
def.resolve(contact);
scope.$apply();
expect(scope.contacts.surname).toEqual('NAME');
expect(scope.contacts.email).toEqual('EMAIL');
});
This give me the following error:
Error: [$rootScope:inprog] $digest already in progress
Now removing the $scope.$apply in the controller causes the test to pass, like this:
UserService.getUser($routeParams.contactId).then(function (data) {
$scope.contacts = data;
});
However this breaks functionality of my controller... So what should I do here?
Thanks for the replies, the $apply is not happening in the UserService. It's in the controller. Like this:
EDIT:
The $apply is happening in the controller like this.
appController.controller('ContactDetailController', function ($scope, $routeParams, UserService) {
UserService.getUser($routeParams.contactId).then(function (data) {
$scope.$apply(function () {
$scope.contacts = data;
});
});
Real UserService:
function getUser(user) {
if (user === undefined) {
user = getUserId();
}
var deferred = Q.defer();
$http({
method: 'GET',
url: BASE_URL + '/users/' + user
}).success(function (user) {
deferred.resolve(user);
});
return deferred.promise;
}
There are a couple of issues in your UserService.
You're using Q, rather than $q. Hard to know exactly what effect this has, other than it's not typical when using Angular and might have affects with regards to exactly when then callbacks run.
You're actually creating a promise in getUser when you don't really need to (can be seen as an anti-pattern). The success function of the promise returned from $http promise I think is often more trouble than it's worth. In my experience, usually better to just use the standard then function, as then you can return a post-processed value for it and use standard promise chaining:
function getUser(user) {
if (user === undefined) {
user = getUserId();
}
return $http({
method: 'GET',
url: BASE_URL + '/users/' + user
}).then(function(response) {
return response.data;
});
}
Once the above is changed, the controller code can be changed to
UserService.getUser($routeParams.contactId).then(function (data) {
$scope.contacts = data;
});
Then in the test, after resolving the promise call $apply.
def.resolve(contact);
scope.$apply();

Categories