My problem is that I don't know where to store data I need to access in the final callbacks for a http request. In jQuery I would just do the following
var token = $.get('/some-url', {}, someCallback);
token.oSomeObject = {data: 'some data'};
function someCallback( data, status, token ){
token.oSomeObject.data // 'some data'
}
I use the token to store request specific data.
Now the only way I find to acheive the this in Angular is to store the data in the actual config:
var config = {
url: '/some-url',
method: 'GET',
oSomeObject: { data: 'some data' }
};
$http(config).success(someCallback);
function someCallback( data, status, headers, config ){
config.oSomeObject.data // 'some data'
}
For one this prevents you from using the short-hand calls ($http.get, $http.post) I also find it's much a much more obtrusive way when wrapping the calls in a specific service module.
Is there any other way of doing this?
Updated to clarify
I'm probably just missing something simple here not understanding how to properly use the promise API, but just to be sure we're on the same page let me give you a bit more detail to the issue.
I have 2 files: 1) Controller.js 2) AjaxServices.js (all ajax calls are defined here as methods on a service).
AjaxServices.js looks like this:
app.service('AjaxService', function( $http ){
var self = this;
this.createUser = function( oUser, fSuccessCallback ){
return $http.put('/api/user', {oUser: oUser})
.success(fSuccessCallback);
}
}
Controller.js looks like this:
app.controller('MyController', function( $scope, AjaxServices ){
$scope.saveUser = function( oUser ){
var oPromise = AjaxServices.createUser( oUser, $scope.onUserSaved );
oPromise.oUser = oUser // this is how I solve it in jQuery.ajax. The oPromise
// is then sent as the token object in the onUserSaved
// callback
}
$scope.onUserSaved = function( oStatus, status, headers, config ){
oStatus.id // here is the id of the newly created user
// which I want to now hook on to the oUser local object
}
}
How would you achieve the same thing using the promise API?
UPDATE 2. Some notes on your updated code:
You don't have to pass the callback to the service. This effectivelly kills the purpose of the promise. Let the service to it's job without coupling it to any consumer of it's data.
app.service('AjaxService', function( $http ){
var self = this;
this.createUser = function( oUser ){
return $http.put('/api/user', {oUser: oUser});
}
}
Now the service does't care about the the callbacks, meaning you could attach multiple callbacks to same service $http call. Ok, let's move on to the service data consumer, in this case it's the controller:
app.controller('MyController', function( $scope, AjaxServices ){
$scope.saveUser = function( oUser ){
var oOriginalPromise = AjaxServices.createUser( oUser );
//lets modify the orginal promise to include our oUser
var oModifiedPromise = oOriginalPromise.then(function(response) {
response.oUser = oUser;
return response;
});
//in the code above we've chained original promise with .then,
//modified response object and returned it for next promise to receive
//at the same time, .then created a new promise
//finally, after modifying our response, we can pass it to the desired callback.
//note, that .success and .error are $http specific promise methods,
//in all other cases use .then(fnSuccess, fnError)
oModifiedPromise.then($scope.onUserSaved);
}
$scope.onUserSaved = function(responseWithUser) {
responseWithUser.oUser;
}
}
Of course, it is still a bit awkward, since the oUser could be saved in the controller's scope and could be accessed directly from there in $scope.onUserSaved.
UPDATE. I will clarify my answer. You can chain promises in any scope, anywhere. Here's another example with token being injected by service:
myModule.factory('Service', function($http) {
return new function() {
this.getData = function() {
return $http.get(url).then(function(response) {
response.token = myToken;
return response;
}
}
}
});
You could even extend or wrap $http service and inject tokens on responses without your services knowing about it.
If you do this with all your requests, maybe a $httpInterceptor would be more appropriate. Read more about intercepting http calls here
Original answer
Since $http provides you with promise, you can chain it to another promise which would inject token in response:
myModule.factory('Service', function($http) {
return new function() {
this.getData = function() {
return $http.get(url);
}
}
});
//in controller or other service:
var myToken;
var tokenizedPromise = Service.getData().then(function(response) {
response.token = myToken;
return response;
});
The final consumer of the promise has access to the token as well
Related
I have an API call that's working great, but I'd like to use it on several controllers so I moved it to it's own service. I'm running into what looks like a classic Scope issue or a misunderstanding of Angular's digest cycle.
'use strict';
myApp.factory('Stuff',['$http', function ($http) {
var Stuff = {};
Stuff.data = {};
Stuff.api = 'http://localhost:8080/api/';
Stuff.getStuff = function() {
var http_stuff_config = {
method: 'GET',
url: Stuff.api + 'stuff/'
};
$http(http_stuff_config).then(function successCallback(response) {
Stuff.data = (response.data);
console.log(Stuff.data); // Returns populated object.
},function errorCallback(response) {
console.log(response.statusText);
});
};
Stuff.getStuff();
console.log(Stuff.data); // Returns empty object.
return Stuff;
}]);
myApp.controller('appController', ['$scope','Stuff',function($scope,Stuff) {
$scope.stuff = Stuff;
console.log($scope.stuff.data); // Returns empty object.
$scope.stuff.getJobs();
console.log($scope.stuff.data); // Returns empty object.
}]);
Here's the big clue. The essential output of above, in order is...
empty object (in service after calling method)
empty object (in controller before calling method)
empty object (in controller after calling method)
populated object (in method execution from service)
populated object (in method execution from controller)
So somewhere between the scope of the getStuff() method and Angular's order of operations, I'm doing something remarkably foolish. Thank you in advance.
You need to add returns on your service, or else the promise will not be returned to the controller. It is not good practice to just store the returns in your services AND NOT return the result to the controller.
This is considered bad practice because, any time you update the data on the service everyone will need to apply $scope.$watch to the service to look for updates. This can be very expensive in large scale apps.
The best Idea is to return the data to the calling controller (if you do not need to cache it, this we can talk about later) and let the controller access it via the promise service.getthing().then(function(result){});
myApp.factory('Stuff',['$http', function ($http) {
var Stuff = {};
Stuff.data = {};
Stuff.api = 'http://localhost:8080/api/';
Stuff.getStuff = function() {
var http_stuff_config = {
method: 'GET',
url: Stuff.api + 'stuff/'
};
return $http(http_stuff_config).then(function successCallback(response) {
return response.data;
console.log(Stuff.data); // Returns populated object.
},function errorCallback(response) {
console.log(response.statusText);
});
};
Stuff.getStuff();
console.log(Stuff.data); // Returns empty object.
return Stuff;
}]);
myApp.controller('appController', ['$scope','Stuff',function($scope,Stuff) {
$scope.stuff = Stuff;
console.log($scope.stuff.data); // Returns empty object.
$scope.stuff.getJobs().then(function(result) {$scope.stuff = result; console.log(result);});
console.log($scope.stuff.data); // Returns empty object.
}]);
I recommend you not to store the result inside the service itself (Stuff.data). Just return your data in the getStuff function and let the appController's scope store the data instead.
remember that $scope.stuff.getJobs() is async
(meaning you can't actually call console.log($scope.stuff.data) on the next line and get the data)
Now if you had a view, with something like <span ng-bind="stuff.data.property"> you could see it work just fine because the view will update by itself when the async function is done. (this is part of angular)
You need to understand that when you run $http, it is making an AJAX request. therefore it will not return an result immediately.
Therefore, if you attempt to use the data coming from $scope.stuff.getJobs(); immediate after invoking this function, you are likely to get nothing.
What you should do is to have your Stuff.getJobs() return a promise, and use promise.then(your own success handler) to correctly handle the returned response.
I have cleaned up your code a little bit. The following is a running sample of your code retrieving data from Yahoo Weather API.
You can play with it on CODEPEN.
html:
<div ng-app="myApp" ng-controller="appController">
<p>{{data}}</p>
</div>
JS:
var myApp = angular.module("myApp", []);
myApp.factory('Stuff',['$http', function ($http) {
var Stuff = {};
Stuff.data = {};
//sample yahoo weather api
Stuff.api = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
Stuff.getData = function() {
var http_stuff_config = {
method: 'GET',
url: Stuff.api + 'stuff/'
};
return $http(http_stuff_config);
};
return Stuff;
}]);
myApp.controller('appController', ['$scope','Stuff',function($scope,Stuff) {
$scope.data = "$http service not ran";
var uncompletedAjaxCall = Stuff.getData();
uncompletedAjaxCall.then(
function(responseData){
$scope.data = responseData;
},
function(errorMsg){}
);
}]);
So far studying existing stackoverflow answers always helped me along, and I could always find an answer, but now I'm really stuck.
I'm building an app, which uses a directive to create calender month type boxes.
<app2directive class="column_50" jahr="2016" mon="November"></app2directive>
the directive code therefore isolates the scope and utilizes a templateUrl file to draw the calendar month
App.directive('app2directive',function( YEARS, MONTHS, DAYS){
return {
restrict:"ACE",
scope:{},
replace:true,
templateUrl:"templates/cal_directive3.html",
controller: function ( $scope, $attrs, $injector, $log, YEARS, MONTHS, DAYS) { var factoryName = "datumFactory" ;
var factoryTonnen = "jsonsrc" ;
var factoryInstance = $injector.get( factoryName ) ;
var tonnenInstance = $injector.get( factoryTonnen ) ;
var wtf = $scope.jsondata.get().then( function( promise){
console.log( "jsondata", promise ) ;
//$scope.tonnen = promise ;
}, function( error){
console.log( "error", error ) ;
}) ;
});
At the moment i use an $injector to inject a factory which runs a $http-request to read a json-file with data such as holidays or other static information specific to the chosen year and month(s).
App.factory( 'jsonsrc', function( $http, $q ){
return {
get: function(){
var deferred = $q.defer() ;
$http.get( 'termine_2016.json' )
.success(function(data, status, headers, config) {
deferred.resolve( data ) ;
}).error(function(data, status, headers, config) {
console.log( "[jsonsrc] request didnot work!" );
deferred.reject( data ) ;
}) ;
return deferred.promise ;
}
}
});
The effect of it is, that the same call to $http is run 12 times for a full year page load.
My concern is to refactor the file, so that I could preferably load the json data into the main-controller and the directive scope could inherit from the parent scope.
By its nature the call returns a promise. The directive would need means to wait for that promise to resolve before it should proceed, but right now I'm stuck on how to go about it. Thanks in advance for any pointers!
First $http is already returning a promise you can do :
return $http.get(...)
PS : you can chain promise so if you have some preprocessing to do you can do
return $http.get(..).then(function(response){
var data = response.data;
[..process..]
**return data;**
}, function(rejection){
// do some stuff
});
Second : Usually you bind data to your directive (ng-model for instance), and call services in controller (the view controller i mean). In order to handle the asynchronous loading of data you use the scope.$watch or attrs.$observe on the model to refresh your directive with the data loaded.
This enforces not to bind the directive with how your data loaded making them reusable, whatever the way you load your data or change it on your application.
Note what I put in bold, you musn't forget that or the next call to then won't have your processed data.
Finally : usually the link function provided by directive API you can just have :
link : function(scope, element, attrs){
attrs.$observe('myVariable', function(){
// refresh your internal state of the directive here
});
}
'myVariable' meanning in the call of your directive you have an attr my-variable :
and "myData" is loaded in the view controllerlike this :
jsonrc.get().then(function(response){
$scope.myData = response.data;
});
If you want to go further I suggest you to build a service for your holidays service so you load the data only at startup of your application :
App.service('MyService',['$http', function($http){
var promise = $http.get([URL]);
return function(){ // this is your service
var me = this;
promise.then(function(response){
this.data = response.data;
});
}
}]);
So now you can use in your main controller : scope.data = MyService.data; or even use it in your directive, or use some getter if you want, this is usually better but not always revelant.
If i forget anything tell me.
I think this could help.
First add the async call into a parent controller (directive's parent
controller).
Then isolate your directive's scope. And add a model to it.
scope: {
data: '=',
}
On your controller add a variable like: $scope.directiveData = {}
Assign the value of that variable with the result of the async call.
Obviously pass it to your directive: <mydirective data="directiveData"></mydirective>
Use this variable on your template with the dataname, or scope.dataon link.
Probably you will need mocked data for directiveData, or just add an ng-if to prevent crashing (when trying to show data the first time, and the directiveData is empty object).
Have your factory save the httpPromise and create it only once.
App.factory( 'jsonsrc', function( $http ){
var httpPromise;
function load () {
httpPromise = $http.get( 'termine_2016.json' )
.then(function onFullfilled(response) {
//return data for chaining
return response.data;
}).catch( function onRejected(response) {
console.log( "[jsonsrc] request didnot work!" );
//throw to reject promise
throw response.status;
});
return httpPromise;
};
function get () {
if (httpPromise) return httpPromise;
//Otherwise
return load();
};
return { load: load,
get: get
};
});
Notice that I removed the $q.defer and instead used the .then and .catch methods. The .success and .error methods have been deprecated; see the AngularJS $http Service API Reference -- deprecation notice.
You can then simplify your directive:
App.directive('app2directive',function(){
return {
restrict:"ACE",
scope:{},
replace:true,
templateUrl:"templates/cal_directive3.html",
controller: function ($scope, $attrs, jsonsrc, $log, YEARS, MONTHS, DAYS) {
jsonsrc.get().then (function (data) {
$scope.tonnen = data ;
}).catch ( function(error){
console.log( "error", error ) ;
});
})
}
});
Implemented this way, the jsonsrc factory executes the XHR GET only once, but each instantiation of the app2directive can retrieve the data for its own isolate scope.
I am new to angular and what I am willing to do is replace a piece of code I wrote in the past in jquery to angularjs.
The goal is to take a string from a span element, split it in two and pass the two strings as parameters in a GET request.
I am trying to learn best coding pratices and improving myself so any comments of any kind are always welcome.
Working Code in jquery:
//Get Song and Artists
setInterval(function () {
var data = $('#songPlaying').text();
var arr = data.split('-');
var artist = arr[0];
var songTitle = arr[1];
//Request Lyrics
$.get('lyricsRequester.php', { "song_author": artist, "song_name" : songTitle},
function(returnedData){
console.log(returnedData);
$('#refreshLyrics').html(returnedData);
});
},10000);
Code in Angular
var app = angular.module("myApp", []);
app.factory('lyricService', function($http) {
return {
getLyrics: function($scope) {
//$scope.songArr = $scope.currentSong.split('-'); <-- **undefined currentSong**
//$scope.artist = $scope.songArr[0];
//$scope.songTitle = $scope.songArr[1];
return
$http.get('/lyricsRequester.php', {
params: {
song_author: $scope.artist,
song_name: $scope.songTitle
}
}).then(function(result) {
return result.data;
});
}
}
});
app.controller('lyricsController', function($scope, lyricService, $interval) {
$interval(function(){
lyricService.getLyrics().then(function(lyrics) {
$scope.lyrics = lyrics; <-- **TypeError: Cannot read property 'then' of undefined**
console.log($scope.lyrics);
});
}, 10000);
});
index.html (just a part)
<div class="col-md-4" ng-controller="lyricsController">{{lyrics}}</div>
<div class="col-md-4"><h3><span id="currentSong" ng-model="currentSong"></span></h3><div>
You need to be careful with your return statement when used in conjunction with newlines, in these lines:
return
$http.get('/lyricsRequester.php',
If you don't, JS will automatically add a semicolon after your return, and the function will return undefined.
Move the $http.get statement to the same line as your return statement.
return $http.get('/lyricsRequester.php', ...
Refer to the following docs:
MDN return statement
Automatic Semicolon Insertion
As for your second issue, you $scope is not really something you inject into your services (like $http). Scopes are available for use in controllers.
You need to refactor your code a bit to make things work.
eg. Your getLyrics function can take a song as a parameter. Then in your controller, you call lyricsService.getLyrics(someSong). Scope access and manipulation are only done in your controller.
app.factory('lyricService', function($http) {
return {
getLyrics: function(song) {
var songArr = song.split('-');
var artist = songArr[0];
var songTitle = songArr[1];
return $http.get('/lyricsRequester.php', {
params: {
song_author: artist,
song_name: songTitle
}
}).then(function(result) {
return result.data;
});
}
}
});
app.controller('lyricsController', function($scope, lyricService) {
$scope.currentSong = 'Judas Priest - A Touch of Evil';
$interval(function(){
lyricService.getLyrics($scope.currentSong).then(function(lyrics) {
$scope.lyrics = lyrics;
console.log($scope.lyrics);
});
}, 10000);
});
You also have some other issues, like using ng-model on your span. ng-model is an angular directive that is used in conjunction with form elements (input, select etc.), not a span as you have. So you might want to change that into an input field.
$http does not use .then, it uses .success and .error. the line that you have where it says then is undefined, should be replaced with a success and error handler instead. Below is a sample from the docs:
// Simple GET request example :
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
See Link:
https://docs.angularjs.org/api/ng/service/$http
I believe this has to do with the way JS Closures work, but I am not totally sure. I am using an AngularJS service to manage the life-cycle of a model that is used within my application. The service uses a combination of fetch() and save() to run GET and POST requests get and update the model from an API. After I fetch() the object, I attempt to place the result into an object sitting in the service where it can be fetched later on. My problem, is that after a successful save(), I take the result and place it into the same object to essentially "update" the object that is on the client with the correct object that is on the server (hence the result of the POST is just an echo of the payload if all is successful).
The problem is that my object is not persisting, and all subsequent calls to save() contain a "stale" object that is not completely updated.
Here is my service:
app.factory('MailboxSubscription', function (API, $q, $stateParams, $rootScope) {
var Subscription = null; //THIS IS MODEL THAT I TRY TO UPDATE CONSTANTLY
var isBusy = false;
var service = {};
var deferred;
var defaultFailure = function(res){
}
service.fetch = function (success, force, failure) {
if(!failure){ failure = defaultFailure;}
if(isBusy){
deferred.promise.then(success, failure);
return deferred.promise;
}else{
deferred = $q.defer();
}
if(Subscription && !force){ // ONCE THE MODEL HAS BEEN FETCHED ONCE, IT STAYS IN MEMORY AND ALL SUBSEQUENT CALLS WILL SKIP THE API CALL AND JUST RETURN THIS OBJECT
deferred.resolve(Subscription);
}else{
//Make the API call to get the data
//Make the API call to get the data
if(typeof(success) === 'function'){
var ServiceId = $stateParams.serviceId;
}else{
var ServiceId = success;
}
isBusy = true;
API.Backups.O365.Exchange.get({id : ServiceId || $stateParams.serviceId}, function(res){
isBusy = false;
if(res.success){
Subscription = res.result; // ON A FIRST-TIME FETCH, THIS API CALL IS USED TO GET THE MODEL
deferred.resolve(Subscription);
}else{
deferred.reject(res);
}
}, function(res){
isBusy = false;
deferred.reject(res);
});
}
deferred.promise.then(success, failure);
return deferred.promise;
}
service.save = function(success, failure){
if(!failure){ failure = function(){};}
if(!success){ success = function(){};}
var deferred = $q.defer();
API.Backups.O365.Exchange.update({id :$rootScope.ServiceId || $stateParams.serviceId}, Subscription, function(res){
if(res.success){
Subscription = res.result; // AFTER AN UPDATE IS MADE AND THE OBJECT IS SAVED, I TRY TO SET THE RESULT TO Subscription.
deferred.resolve(res);
}else{
deferred.reject(res);
}
}, function(res){
deferred.reject(res);
});
deferred.promise.then(success, failure);
return deferred.promise;
}
service.get = function(){
return Subscription;
}
return service;
});
So the problem appears to stem from trying to use Subscription as a centralized resource for storing the model, but the model is not updating correctly.
If you are looking to have that Subscription model updated throughout the service, I'd suggested when you call MailboxSubscription.fetch() and MailboxSubscription.save()in your controller, you use MailboxSubscription.get() in the .then() method of your calls.
// get initial value of Subscription model
$scope.Subscription = MailboxSubscription.get();
// let's fetch
MailboxSubscription.fetch().then(
// callback
function() {
// let's get the updated model
$scope.Subscription = MailboxSubscription.get();
},
// errback
function() {
// handle error
}
);
// let's save
MailboxSubscription.save().then(
// callback
function() {
// let's get the updated model
$scope.Subscription = MailboxSubscription.get();
},
// errback
function() {
// handle error
}
);
Also, I've created a working jsfiddle simplifying your use case. It works fine. Maybe there is something that can be gleamed from that (I am using $timeout to spoof your API calls).
I have two ajax calls in a service; the first one, AjaxOne gets the data I want from fields (user entered), I then want to alter the data by passing it to another ajax call, AjaxTwo to get the results I need. Both ajax calls are completely different services and can be interacted with by multiple controllers so I've placed then in their own unique Angular factory methods (could be service).
Issue is I'm thinking traditional sequential code running akin to PHP in my little semi-sudo code below (which I know will not work but just for example of how I would solve it in PHP), but I know I need to be thinking in parallel but can't quite get my head around what I need to do for the controller to be able to pass the results from AjaxOne to AjaxTwo. Keep in mind that both factory methods don't need to know of each other existence (to create no coupling and make then highly reusable).
How would I go about doing what I need to with Angular?
app.controller('app', function( $http, $scope, AjaxOne, AjaxTwo ) {
$scope.fields = '';
$scope.ajaxOne = AjaxOne;
$scope.ajaxTwo = AjaxTwo;
$scope.results = [];
$scope.process = function () {
AjaxOne.getResults($scope.fields);
$scope.results = AjaxTwo.getResults(AjaxOne.results);
};
});
Thanks.
Seems like you need to adjust your AjaxOne service to accept a callback, which would asynchronously call AjaxTwo only when AjaxOne is done doing whatever it does:
// Inside AjaxOne:
$scope.getResults = function(things, cb) {
// do something with `things`. Let's assume you're using $http:
$http({
url: "http://example.appspot.com/rest/app",
method: "POST",
data: {
"foo": "bar"
}
}).success(function(data, status, headers, config) {
cb(data);
});
};
// In your original example:
app.controller('app', function($http, $scope, AjaxOne, AjaxTwo) {
$scope.fields = '';
$scope.ajaxOne = AjaxOne;
$scope.ajaxTwo = AjaxTwo;
$scope.results = [];
$scope.process = function() {
AjaxOne.getResults($scope.fields, function(resultsFromAjaxOne) {
$scope.results = AjaxTwo.getResults(resultsFromAjaxOne);
});
};
});
You should use the promises that you get with the $http service it will give something like this
app.controller('app', function( $http, $scope, AjaxOne, AjaxTwo ) {
$scope.fields = '';
$scope.results = [];
$scope.process = function () {
AjaxOne.getResults($scope.fields).success(function(results){
AjaxTwo.getResults(results).success(function(results2){
$scope.results = results2;
});
});
};
});
for more information you can check this url http://docs.angularjs.org/api/ng/service/$http