FAQ Database Discussion Community


Using a ui-router resolve to wait for a google map to load

angular-ui-router,angular-promise,angular-google-maps
I'm trying to load a google map before loading the dashboard state. Seems like the perfect use for a ui-router resolve. Unfortunately, the uiGmapIsReady promise is never resolving. Any help would be greatly appreciated. state('app.dashboard', { url: '/dashboard', templateUrl: 'partials/dashboard.html', controller: 'dashCtrl', data: { authorizedRoles: [USER_ROLES.all] }, resolve: { getGoogleMap:...

Unit testing promises in js-data-angular models

angularjs,angular-promise,jsdata
We use js-data and js-data-angular in our project. I have the following model: (function () { 'use strict'; angular.module('dash.models') .factory('Diagnosis', ['DS', function (DS) { function transform(resourcename, attrs, cb) { attrs.icd9codes.forEach(function (el) { delete el.add; }); cb(null, attrs); } this.transform = transform; return DS.defineResource({ name: 'diagnosis', idAttribute: 'id', endpoint: '/diagnosis', baseUrl:...

How to properly mock an Angular Promise returned from $http

javascript,angularjs,unit-testing,jasmine,angular-promise
I have been fighting with this for a little bit now and need some guidance. I would like to unit test this angular service... specifically, the failed part of the promise. (function () { angular.module('testable') .factory('myService', ["$http", "$q", function ($http, $q) { return { createThing: function(thing) { return $http.post("//...", thing)...

Looping async function over array with $q in angularjs

javascript,angularjs,asynchronous,angular-promise
My goal is to take an array of image URLs (obtained from an API, their CORS headers are set) and to loop over it, fetching each image using xhr, resizing it in a canvas element and then generate another array whose entries are the data for the resized images. My...

Angularjs $http delete with $q promise leads to TypeError: object is not a function

javascript,angularjs,rest,angular-promise,angular-http
The following snippet returns the following error: TypeError: object is not a function service.deleteItem = function(itemId) { var def = $q.defer(); $http.delete(SERVER_REST_PATH + '/items/' + itemId) .success(function() { def.resolve(); }).error(function(data, status) { def.reject("Error deleting the item"); }); return def.promise(); }; If I rewrite it as the following it works: service.deleteItem...

Angular forEach wait until all promises are complete?

angularjs,coffeescript,promise,angular-promise,cloudinary
I'm doing a forEach loop and that makes an API call to Cloudinary, and I'm building an array with the response data. Once the data is collected, I need to send it to some other API. How do I wait on the promises getting resolved and the data collected before...

Conditional Chaining of $http-calls with Promises in AngularJS

javascript,angularjs,angular-promise
I have to execute three different $http-calls sequentially which depend on each other. Until now my working solution ist something like this $http.get(".../1/...").success(function(){ $http.get(".../2/...").success(function(){ $http.get(".../3/...").success(function(){ }); }); }); Now there is a certain change to be made: The first call should be skipped if a condition is true. I could...

How to mock Angular $q service in Jasmine test?

javascript,angularjs,unit-testing,jasmine,angular-promise
I am trying to test an Angular service, which has 2 dependencies, one on $q and another one on 'myService' which also has dependency on $q. (function() { 'use strict'; angular.module('myModule').factory('myService', [ '$q', 'apiService', function($q, apiService) { var data = null; function getData() { var deferred = $q.defer(); if (data...

Angular Controller Not Waiting for Service Promise to Resolve

angularjs,angular-promise
I have an Angular service that looks like this: (function () { 'use strict'; var serviceId = 'currentUserService'; angular.module('app').factory(serviceId, ['common', 'datacontext', currentUserService]); function currentUserService(common, datacontext) { var $q = common.$q; var getLogFn = common.logger.getLogFn; var logError = getLogFn(serviceId, "error"); var user = {}; var service = { user: user, doesUserHaveFeature:...

AngularJS reject a promise in success callback

javascript,angularjs,promise,angular-promise
I'm using $q to check if two resources' queries have been resolved or not. Like this: $q.all([ ResourceA.get({}, function success(data) { console.log("got A"); }).$promise, ResourceB.get({}, function success(data) { console.log('got B'); }).$promise ]).then(function() { console.log("done"); }); The question is, the data I'm receiving in each of the success functions might not...

Can this promise nesting be changed to chaining?

javascript,angularjs,nesting,chaining,angular-promise
This is the pseudo scenario | then (items) | then (items, actions) getItems() | getActions(for:items) | apply(actions -> items) :promise | :promise | model <= items | | :synchronous So in words: I need to get a list of global items. Fine. Items fetched. Make a request for actions that...

q.all not working for multiple promises

angularjs,angularjs-scope,angular-promise
I have the following q.all calling to resolve two promises. I checked all the posts and tried all other ways of implementation q.all and its the same case var xyzdeffered = $q.defer(); service1.getServiceDetail1($routeParams.id).then(function(promise) { xyzdeffered.resolve(promise); }); var abcdeffered = $q.defer(); service2.getServiceDetail2($routeParams.id).then(function(promise) { abcdeffered.resolve(promise); }); $q.all([ xyzdeffered, abcdeffered ]).then(function(data) { $scope.variable...

Executing then after catch

javascript,angularjs,angular-promise
I have the following fiddle: http://jsfiddle.net/thelgevold/3uv9nnjm/6/ angular.module('hello',[]).controller('helloController',function($q){ console.clear(); function someService(){ var deferred = $q.defer(); deferred.reject({e:'error'}); return deferred.promise; } function callService(){ return someService().then(function(obj){ console.log('first then'); }). catch(function(e){ console.log('error1'); var deferred = $q.defer(); deferred.reject({e:'error'}); return deferred.promise; }); } callService().catch(function(e){...

Resolve promise in service without callback in controller

angularjs,callback,controller,promise,angular-promise
I would like to ask/discuss wether this is good or bad practise - what are the pros and cons of making a service call insde a controller as clean and short as possible. In other words: not having a callback anymore but make use of the Angular binding principles of...

angular $http promise being returned twice

javascript,angularjs,angular-promise
I am trying to evaluate an expression in an if statement to return true or false. The function's evaluation depends on $http promises, of which the documentation out there is plentiful—so I'm confident I can get this figured out. However, I noticed something odd in my console, and that is...

Why doesn't my $q resolve and promise work like I think it does?

javascript,angularjs,angular-promise
I'm always having problems with $q Here is an example where the .then is fired right away function doit() { var deferred = $q.defer(); var modalInstance = $modal.open({ template: '<p>this is modal</p><a ng-click="ok()">ok</a>', controller: function ($scope, $modalInstance) { $scope.ok = function () { $modalInstance.close(); }; } }); modalInstance.result.then(function () {...

angular routing with ng-include

angularjs,routing,angularjs-routing,angular-promise,angularjs-http
It's a little complex to describe my problem.Now I have two pages to be routed. One is project.jsp,the other is ticket.jsp.The latter can be included in the former using ng-include. In index.jsp,I use ng-view. index.jsp <div ng-view></div> In app.js,I do the routing config and create controllers. $routeProvider.when('/tickets', { templateUrl: 'ticket.jsp',...

Chaining .then()-calls: Rejection not recognized

angularjs,promise,angular-promise
I'm having a difficult time understanding the idea of promises (in angularjs). I thought that I could define a function that returns a promise. The consumer of this promise can work with it, and might return some data or a promise as well. But this simple example behaves unexpectedly: The...

Flow control of processing ajax requests (i.e. only processing the next request after the previous request has completed)

javascript,ajax,angularjs,angular-promise
I have written the following code but I'm have a problem with assigning $scope.sessionKey = data.result; before it gets passed in the next ajax call result.params.sSessionKey = $scope.sessionKey (and yes result.name=='get_session_key' evaluates for the first iteration of the loop). As you can see I've tried having a go with $q...

AngularJS service gets the data, but doesn`t return it to the controller?

javascript,angularjs,angularjs-service,angular-promise
scope.membersWarnings in controller is always empty, but in service it gets the data from the server. Somehow my data from the server is lost between callback of get function in service and controller. Controller: AndreaApp.controller('MemberDetailController', ['$scope', '$rootScope','$http','$location','$routeParams','MemberService','MemberGroupsService','ArrivalsService','WarningsService','NotificationsService',function (scope,rootScope,...

need to handle session time out using promises ($q) in Angularjs application

jquery,ajax,angularjs,angularjs-service,angular-promise
I am trying to convert my existing jquery Ajax request to use Angularjs Promises. I am not able to figure how to include fail condition in my promises. Except that remaining things are working fine. Earlier I had my jquery Ajax call as shown below. Here when I make an...

What is the best way to implement promise in the given scenario?

javascript,jquery,promise,angular-promise,gameclosure
I'm using D.js as promise library for our javascript application. Following is my sample code: function getData(deferred) { var data_one; // getInfo is returning a promise for async task getInfo() .then(function (resp_one) { data_one = resp_one; // getInfo2 is also returning another promise return getInfo2(); }) .then(function (resp_two) { deferred.resolve('prefix'...

Angular logs error to console before raising promise.catch

angularjs,promise,angular-promise
I feel like I am going a little crazy, but Angular appears to throw an error for a promise even if I have a catch defined. It throws the error to the console, then allows the catch to run. Here is a super-simple fiddle The test code: $q.when(1) .then(function() {...

use angular factory to hold a value for rest of application to access to minimize server calls

javascript,angularjs,promise,factory,angular-promise
I have the following factory: angularModule .factory('ArticleCategoryService', function ($http, $q) { // Service logic // ... var categories = []; var _getCategories = $http.get('/api/articles/category').success(function (_categories) { categories = _categories; }); // .error( function (data, status, headers, config) { // }); // Public API here return { getCategories: function () {...

Resolving promise objects based on value - angularjs

javascript,angularjs,promise,angular-promise
I read in docs.angularjs.org that on a deferred object, a promise is resolved with a value and here are my couple of questions. var dfd = $q.deferred(); dfd.resolve() - what happens when resolving without a value? Is it a rejection? resolve(value) – resolves the derived promise with the value. If...

How to chain a series of functions which return promises, and require different parameters?

javascript,angularjs,angular-promise
I have two asynchronous functions, which use parameters already acquired somehow: var a = getUserinput(); var b = getUserinput(); var c = getUserinput(); var d = getUserinput(); var func1 = function(valA, valB){ var deferred = $q.deferred; //http call with valA, valb... // when complete, resolve deferred return deferred.promise; } var...

A combined promise is resolved before any sub-promise is resolved

javascript,angularjs,angular-promise
I am using AngularJS and its $q. I wrote a service as follows: Get.$inject = ['$q', '$http']; function Get($q, $http) { return { get: function(url) { var deferred = $q.defer(); $http.get(url + '?' + Math.random()).success(function(data) { alert('Got data: ' + JSON.stringify(data)); deferred.resolve(data); }); return deferred.promise; } } } and used...

ControllerProvider in UI-router results in error

javascript,angularjs,angular-ui-router,angular-promise
I have a ui-router StateProvider and need to pick between controllers & views based on external data, so I used TemplateProvider and ControllerProvider. If I only had the TemplateProvider it all works fine, but when I add the ControllerProvider I get this error: Error: [ng:areq] Argument 'fn' is not a...

$http promise chain running in wrong order

javascript,ajax,angularjs,promise,angular-promise
I am new to angularjs. My goal is very simple. I want to make an ajax call to get data and, once complete, I want to make a second call to get another set of data that is dependent on information in the first set. I'm trying to do this...

How to get data result from service in angular

angularjs,http,angular-promise
I have to get the data which comes from API and in this case I used a controller and a service, it's service `daryo.factory('daryoSvc', ['$http', function ($http) { var categories = []; var categoriesjon = function () { $http.get('http://localhost:18737/Category/GetCategories'). success(function (data, status, headers, config) { categories = { "one": "two",...

Angular $q.reject().success(), does that make sense?

javascript,angularjs,promise,angular-promise
I'm reading a book called MEAN Machine, and as I'm getting to the late chapters, I've got stuck at one of the sample applications, that doesn't seem to work. The problem seems to occur because my mainController calls authService's Auth.getUser() method, which may return either a $http.get() or a $q.reject()....

Angular Promises - Jumping from the success to the failure callback?

javascript,angularjs,angular-promise
I feel like I may be doing something that Promises weren't designed to do, but here we go, this is what I'd like to do: $http.get('/api/endpoint/PlanA.json').then( function success( response ) { if ( response.data.isAllGood ) { $scope.myData = response.data; } else { // TODO HERE! Call the failure function! }...

Angular - multiple promises wrapped in one promise

javascript,angularjs,angular-promise
I have a couple of services that return the same type of objects just a different type via a flag on the object. These services have functions that return a promise. Service 1 - getPlaces: this.getPlaces = function () { return $http.get('http://somewhere.com').then(function (response) { return response; }).catch(exception.catcher('Something went wrong')); };...

Is this a “Deferred Antipattern”?

angularjs,angularjs-directive,angularjs-service,angular-promise
I'm finding it hard to understand the "deferred antipattern". I think I understand it in principal but I haven't seen a super simple example of what a service, with a differed promise and one with antipattern, so I figured I'd try and make my own but seeing as how I'm...

Asynchronous Angular Promise and Variable Initialization

javascript,angularjs,asynchronous,angular-promise
I have a factory that looks like such: app.factory('thingFactory', function($http) { var factory = {}; var things = []; factory.refreshThings = function() { return $http.post('/GetThings'); } factory.initializeThings = factory.refreshThings() .then(function(response) { things = response.data; }, function(response){ // some error handling code here... }); factory.getThings = function() { return things; }...

Angular HTTP within a HTTP Interceptor

javascript,angularjs,angular-promise,angular-http-interceptors
I need to append the necessary HMAC headers to a request. This should not be very difficult however I am starting to get frustrated. What is wrong with the following code. The actual http call I am doing works; I have run this call myself and it returns the necessary...

Function Automatically Called Inside Javascript Promise

javascript,angularjs,angular-promise,ng-dialog
I'm fairly new to Javascript promises, and running into an issue that I can't hunt down anything about via Google or Stack Exchange. When I refer to a function in a .then chained off a promise, I sometimes have to wrap that function in an anonymous function in order to...

Angular Promises: Best Practices and Pros/Cons of Different Techniques [duplicate]

javascript,angularjs,promise,angular-promise
This question already has an answer here: What is the explicit promise construction antipattern and how do I avoid it? 3 answers I'm learning Angular and I've come across two approaches to make calls that return promises. I'd like to know if one approach is better than the other...

How do I return a promise from my service to my controller?

javascript,angularjs,angular-promise
I have asked this is several variations but I now have some definitive code that contains a bug I can't dig out. I have an Angular service like this: .service("lookupDataService", [ '$q', '$http', '$timeout', function($q, $http, $timeout) { this.brokers = function() { var cachedBrokers = localStorage.getItem("brokers"); if (!cachedBrokers) { return...

AngularJS wait for simple promise to be resolved

javascript,angularjs,angular-promise
I'm really new with AngularJS and WebApi and I can't figure out how to wait for promises to be resolved. I have a very simple application. This is my HTML code: <body ng-app="PersonApp"> <div ng-controller="PersonController"> <div id="personTable"> <table> <tr ng-repeat="p in person"> <td>{{ p.surname }}</td> <td>{{ p.name }}</td> <td>{{ p.birthDate...

AngularJS $q.all update/notify not called why?

angularjs,q,angular-promise
So I have a simple example of using $q.all to batch $resource calls, what I want to know is why is my update handler never called? I would have thought it would be called after each promise is successfully completed? Only the result handler is called. What am I doing...

Angular Promise Called Twice is Only Deferring to First Caller

angularjs,jsonp,deferred,angular-promise,angular-services
I'm working on a video series app that's set up like so: angular.module('videoSeries', ['ngAnimate', 'ui.router']) .config(config) .factory('episodes', episodesFactory) .controller('MainCtrl', MainCtrl) .controller('EpisodeCtrl', EpisodeCtrl); The factory 'episodes' loads a JSONP file that both controllers need to read from. In order to ensure that the controllers wait until the JSONP has successfully returned,...

angularjs return another promise in $q.all

angularjs,q,angular-promise
in my angularjs/ionic application I'm getting data from a sqlite database and want to get data from a web service which depends on the values of the database variables. I thought this might be possible with: .factory('WebSrvs', function($http,DatabaseSrvs) { var getData = function() { var promiseReceiverUrl = DatabaseSrvs.getLocalValue('value1'); var promiseVehicleId...

Cannot execute chained promises

javascript,angularjs,angular-promise
I need to get feed using $http.jsonp after that I return deferred.resolve(feed) which should pass feed value to chained function EntryStateUrlService.getEntryStateUrl. For some reason it says FeedService.parseFeed(feedSrc) evaluated as undefined therefore then() method cannot be invoked on undefined. How to fix it? app.service('LoadData', ['FeedService', 'EntryStateUrlService', '$q', function(FeedService, EntryStateUrlService, $q) {...

Angular, mocking a promise with settimeout ($q)

javascript,angularjs,angular-promise
I am try ing to set up a test harness for a service, making it take about 1 second to play around with some stuff on the front end. I am using a q so I can call a .then in the controller, so I figuired I could fake this...

Angular JS Jasmine Testing - Multiple Changes in Variable Value in Chained Promise

angularjs,jasmine,angular-promise
I have a chained promise that looks like: myService.methodOne().then(function(){ $scope.myVariable = true; return myService.methodTwo(); }) .then(function(){ $scope.myVariable = false; }); How would I test that myVariable was first assigned to true then to false?...

Angular deferred promise

javascript,angularjs,angular-promise
I have a function that returns deferred promise in Angular. I have used $$state to access its values from calling class but not sure if this is the right way. Should I use .then instead or is there any standard way to access a specific variable for $q.deferred Promise object?...

How to test .notify for .then in angularjs

javascript,angularjs,deferred,angular-promise
In this post function var deferredRespond = $q.defer(); var statusNotice="Loading..."; deferredRespond.notify(statusNotice); $http.post(processorUrl,{ params:request, }).success(function(respondData){ //deferredRespond.resolve(respondData); /*For Test Rejected Defer! -awh*/ deferredRespond.resolve($q.reject("Simulated Reject")); //deferredRespond.resolve($q.notify("Simulated LOADING...")); }) .error(function(){ deferredRespond.reject('Failed defer!'); }); I am able to simulate .reject by doing .resolve($q.reject But I wonder why I can not...

$q: default reject handler

javascript,angularjs,promise,angular-promise
I want to return a $q instance so that if clients don't call 'then' with a reject handler, then a default one runs. E.g. assume the default is to alert(1) Then mypromise.then(function(result){...}) will alert 1 but mypromise.then(null, function(reason){alert(2)}) will alert 2...

Problems with returning data from simple function to UI-router resolve

angularjs,angular-ui-router,angular-promise
I have tried all the methods I can find that suggest returning a promise object to the resolve, so that my function will process asynchronously, but still I cannot get the correct data returned - please advise : .state("app.deals.private", { url: "/private/", resolve: { dealsFeatured: function(Deals, $rootScope) { return Deals.getDeals('FEATURED',...

How to structure an Angular service so it can handle asynchronous calls?

angularjs,asynchronous,promise,angularjs-service,angular-promise
In my Angular application, I have two controllers which both need access to the same data. Toward that end, I've created a service which will be responsible for holding and providing access to that data: angular.module("SomeModule").factory( "SomeService", function( $http ) { var svc = {}; var data = {}; //...

Chaining nested promises in the loop

angularjs,angular-promise
There is a controller that gets say countries and their cities using the service which uses $http.get() to fetch data from the server. Both the countries and the cities are json arrays. Current implementation service service.getCountries = function() { return $http.get('url'); } service.getCities = function(country) { return $http.get('url' + country);...

How to get variables properly with Angularjs promises

javascript,angularjs,angular-promise
I couldn't figure out this problem. My question is why I cannot resolve responses. And I cannot use the responses in my controller. But I get 6 responses as empty. Please open console and push "Get Result" button under the google map. You will see undefined array. here is plunker...

service method does not recognize variable defined outside

javascript,angularjs,angular-promise,angular-resource
Here is a service: angular.module('core').factory('ServerErrorAlert', ['toaster', function(toaster) { return function(errorResponse) { toaster.pop('error', 'Error', errorResponse); if (deferred) { deferred.reject(errorResponse); } } } ]); Here is how I call it : function update(updatedTransaction, originalTransaction, updateLocal) { var deferred = $q.defer(); updatedTransaction.$update(function() { if (updateLocal) {angular.extend(originalTransaction, updatedTransaction);} deferred.resolve(updateLocal ? originalTransaction : false); }...

Make angular.forEach wait for promise after going to next object

javascript,angularjs,foreach,promise,angular-promise
I have a list of objects. The objects are passed to a deferred function. I want to call the function with the next object only after the previous call is resolved. Is there any way I can do this? angular.forEach(objects, function (object) { doSomething(object);//wait for this to resolve and after...

Load data during angular config state

angularjs,angular-promise
Introduction: A third-party navigation directive for an application sidebar, recommends loading data during the configuration phase. The menu items are dynamic, and are resolved on the server based on user credentials. Problem Statment: While the data loads fine, the then() clause defined in the code below is never executed, and...

How to read array of files in a factory in Angularjs?

javascript,angularjs,asynchronous,angular-promise
I have an array of files. I want to read all of them and make a json array out of it. The problem is that d3.csvis an asynchronous function. From this question, I have come to know that $q.defer() has to be used to returned deferred promise to the controller....

Promise chaining and dealing with an action not returning anything down the chain of promises

angularjs,angular-promise
I have a question regarding Javascript promise chaining. Say I have an action somewhere down a chain of promise. That action does not return any value but it must complete before the chain can proceed. Do I need to wrap that action in a promise? Do I need something like:...

Aborting ngResource using a promise object

javascript,angularjs,angular-promise,angular-resource
I've recently learned that ngResource request can be aborted either by specifying a timeout in ms or passing a deferred object. The second solution does not seem to work for me, and I have no idea what I'm doing wrong. I've created a fiddle to demonstrate the problem http://jsfiddle.net/HB7LU/10977/ var...

Return promise in AngularJS $http.get?

javascript,angularjs,node.js,angular-promise
I'm trying to return the values I get in my $http.get but I can't get it to work... $scope.getDecision = function(id) { var defer = $q.defer(); $http({ method: 'GET', url: 'http://127.0.0.1:3000/decision', params: {id: id}, headers: {'Content-Type': 'application/x-www-form-urlencoded'} }).success(function(data, status, header, config) { console.log(data); //----> Correct values defer.resolve(data); }).error(function(data, status, header,...

Confusion on promise objects

javascript,angularjs,promise,angular-promise
I've read about promise objects and infact have worked on promise objects but still I must say I'm not clear on the basics. $http.get('/someURL').then(function(response) { // do something }, function(error) { }); People say that .then returns a promise object. In the above example $http.get() returns a promise object. So...

$q resolve function not triggering then

javascript,unit-testing,angular-promise
I thought I was using the AngularJS $q interface correctly. But the function I'm passing to the then callback is never being executed. And I am calling resolve in the function which is wrapped by $q. I've verified that resolve() is being called, yet it seems this is not the...

AngularJs ng-options with promises issue

angularjs,angular-promise
I am creating a page with a form where is it possible to modify a job. When the page loads the following promise chain is fired which gets the current job data and populates the form. I am having an issue with the city select because only when the job...

writing an $httpProvider for a long-polling comet app

angularjs,promise,comet,long-polling,angular-promise
TL;DR: Are there examples of Angular with long-polling integration out there? (Examples, specifically Comet examples would be nice!) Our current app uses Angular and Comet. The client sends out long-polling requests that stay open until the server has data to return. When the server returns data, the data payload might...

ui-router resolve showing previous resolve result on first load, sometimes not showing at all on reloads

javascript,angularjs,angular-ui-router,angular-promise
So I have it structured like this. Relevant state code: resolve:{ projectPromise: ['$stateParams', 'projects', 'session', function($stateParams, projects, session){ projects.getProject($stateParams.id).success(function(data){ session.currentProject = data; }); }] } getProject: o.getProject = function(project_id, container){ return $http.get('/project/' + project_id); }; Inside of the relevant controller: $scope.currentProject = session.currentProject; And inside of the relevant template: {{currentProject.title}}...

Deferred Promises with AJAX in Angular

ajax,angularjs,angular-promise
I'm trying to send data to my view from an AJAX call to my API. I am able to successfully hit my API and get data, but I was having problems with the view rendering before the AJAX call came back. I'm trying to wrap my AJAX call in a...

Connecting a promise through two services

javascript,angularjs,angular-promise
I'm a bit new to angular and am trying to understand how I can use a promise with two services. In the code below in the App.js I call FirstService.get(), which should wait for the RestService to return the result. In the App.js I would like to use the .then()...

access angularjs deferred promise from new template

angularjs,angularjs-service,angular-promise,angularjs-factory
I'm new to angular and LOVE it...coming from a 10 yr PHP background there is a lot of new terms for me. Here is what I would like to-do, not sure if it's possible, if yes, not sure how. I have created a list of properties and that part works...

Why return the promise and the data when using $http in an Angular service?

javascript,angularjs,angular-promise,angularjs-http
I frequently see tutorials and snippets online about Angular services to make $http calls that return both the $http promise and some data. If the promise is returned to the controller, what is the point of returning the data in the service? I don't even understand to where it is...

Intercept Unathorized API calls with Angular

javascript,angularjs,interceptor,angular-promise
I am trying to intercept the 401 and 403 errors to refresh the user token, but I can't get it working well. All I have achieved is this interceptor: app.config(function ($httpProvider) { $httpProvider.interceptors.push(function ($q, $injector) { return { // On request success request: function (config) { var deferred = $q.defer();...

Behavior on AngularJS deferred object

ajax,angularjs,deferred,angular-promise
I was writing a function that will be executed asynchronously. Suddenly a question popped up in my mind. Let's say I have the following function for updating student records. module.factory('StudentService', function($http, $q) { var service = {}; service.updateStudent = function(studentData) { var deferred = $q.defer(); $http.put('http://www.example.com/student/update', studentData, { headers: {...

Managing angularjs nested promises to build response back from the server

javascript,angularjs,angular-promise
Im building a response back from the server using angular in order to show private messages. So far i have this code which works fine but it doesnt look like using promises the correct way, specially for handling errors. Im wondering how im suppose to handle nested promises in a...

How to return a promise with ngresource post

ajax,angularjs,promise,angular-promise,ngresource
Been trying to figure out how to return a promise with ngresource post. I can do it with $http but cant figure this out. I am getting .then is not defined error. Controller $scope.addLocation = function (model) { var model = $scope.model; var promise = DocumentLocation.save(model); promise.then(function success(model) { console.log(model);...

Retrieving value of inner promise

javascript,angularjs,location,promise,angular-promise
I am trying to access the value of a nested promise from a controller. Here is my controller. I am calling my service, expected a city name to be returned: LocationService.getCurrentCity(function(response) { // This is never executed console.log('City name retrieved'); console.log(response); }); And here is the service. I am updating...

Calculate function after function execution finished - data result exists not return always correct result

angularjs,typescript,angular-promise
That's not really the case of using promisses - because the result is a result of many service calls - in rder to fill an array of car.Make <td ng-show="IsOK(obj)" class="text-center"> <img ng-show="GetStatus(obj)==''" src='@Url.Content("~/img/spinner.gif")' /> <span class="label label-success" ng-bind="GetStatus(obj)"></span> </td> IsValid = (car: Car): boolean => { return (car.Title !=...

Dealing with non-idempotent $http requests in Angular

javascript,angularjs,angular-promise
I'm having trouble conceptualizing how to model/access data from a non-idempotent request throughout my application. As an example we'll say I have an API that returns a random author for a user to view. I need to display info about this author in various places in the app, and then...

Rethrowing exceptions in nested promise chains

javascript,angularjs,promise,angular-promise
I'm trying to figure out a clean way to chain promises in AngularJs. My goal is to not rewrap the $http promise using $q and to instead take advantage of the fact that $http.xxx() methods return promises and use chaining. In the below code I'm trying to satisfy the following...

Prevent Angular $httpProvider interceptor from firing on template loads

javascript,angularjs,angular-promise
Want a simple interceptor that will fire a logging method on every 200 status. This was easy to setup, but now I'm noticing that all of my Angular templates are loaded via $httpProvider as well and thus triggering my 200 interceptor. Any way to differentiate between template loads and actual...

$http promise always returns original promise?

javascript,angularjs,angular-promise
I apologize if this isn't a good question, but it's something that's confusing me a bit. I'm attempting to return specific data from an $http.post() from within a factory, however it would appear that $http always return the original promise. I'm looking to avoid .success and .error given their possible...

Issue with Angular Js resolve method

angularjs,angular-ui-router,promise,angular-ui,angular-promise
Hi I have a $stateProvider like below. $stateProvider .state('team.details', { url: '/:teamId', views: { '@': { controller: 'teamDetailsCtrl', templateUrl: 'src/modules/team/details/teamDetails.html', resolve: { user: function ($stateParams, TeamResource) { return TeamResource.get({ teamid: $stateParams.teamId }).$promise; } The TeamResource.get is calling a rest api and everything is working fine if the data is sent...

waiting for $http.get call to complete

angularjs,angular-promise
I know this has something to do with promises but I'm having a hard time understanding how to implement them. My controller: angular.module('landingApp') .controller('MainCtrl', function($http, $q){ var main = this; main.favoritesIds = []; $http.get('api/v1/planograms/get_favorites') .success(function(data){ for(var i=0; i < data.planograms.length; i++) main.favoritesIds.push(data.planograms[i].id); }); main.isFavorite = function(planogram_id){ return main.favoriteIds.indexOf(planogram_id) > -1;...

ui-router: async data in templateUrl function

javascript,angularjs,angular-ui-router,promise,angular-promise
I've run into quite a novel problem with ui router. I'm basically trying to query my API for a template url, which is stored and returned as a Resource object. The problem, is it seems that the templateUrl function is returning as undefined. My code is as follows: (function() {...