How to check xmlhttpRequest in AngularJS - javascript

How to check XMLHttpRequest While I'm getting status as 200 why it's not checking my xhr
angular.module("productManagement").controller('Employee', function ($scope, EmployeeService) {
var xhr = new XMLHttpRequest();
$scope.GetdataBySubmit = function () {
var GetData = EmployeeService.GetEmployeeData();
debugger;
GetData.then(function(d) {
if (xhr.status == "200") {
$scope.Employee = d.data;
$('#TadleData').show();
} else {
console.log("")
}
})
}
})
Here I'm Updating My GetEmployeeData Code
angular.module("productManagement").service("EmployeeService", function
($http) {
this.GetEmployeeData = function () {
var x=$http({
url: "http://localhost:9632/Api/Employee",
method:"Get",
data:JSON.stringify()
})
return x;
}
})

No need to define and use xhr variable
As you are using $http and returning Promise, Use the success callback handler response object.
GetData.then(function (response) {
if (response.status == 200) {
$scope.Employee = response.data;
$('#TadleData').show();
}
}, function (response) {
console.log("Do something on error")
})

Related

passing error message from service to controller in angularjs

Controller.js
var vm = this;
vm.admin = {};
vm.add = function () {
API.addAdmin(token, vm.admin)
.then(function (resp) {
vm.hideForm = true;
vm.showButton = true;
Notify.green(resp);
}, function (resp) {
Notify.red(resp);
});
};
API.js
function addAdmin(token, dataObj) {
return Constant.getApiUrl()
.then(function (url) {
$http({
method: 'POST',
url: url + '/client/admin',
headers: {
'Token': token
},
data: dataObj
}).then(handleResp);
function handleResp(resp) {
var responseStatus = (resp.status >= 200 && resp.status < 300) ? 'good' : 'bad';
if (responseStatus === 'good') {
console.log("Success" + resp);
return resp;
} else {
console.log("Failed" + resp);
return resp;
}
}
})
}
If I get a success response in API then i need to connect it to success function in my controller and if i get error message in my API, then i need it to connect it to error function in my controller.How should I evaluate the response status from my API(is either success or error).
I don't want to pass successfn, errorfn from my controller to API(only if there's no alternative).
I need to get the response data from API to controller to show it in Notify message.
Thank You!
In service (assign response values in "originalData"):
angular.module('appname').service('myserviceName', function(yourExistingService){
this.myFunction= function(originalData) {
//for next line to work return promise from your addAdmin method.
var promise = yourExistingService.getResponseFromURL(originalData);
return promise;
}
});
And in your controller :
var promise = myserviceName.myFunction($scope.originalData);
promise.$promise.then(function() {
console.log($scope.originalData);
});
And then you can check you "originalData" and write code according to your need.For more detail you can have a look on this http://andyshora.com/promises-angularjs-explained-as-cartoon.html.

Angularjs FB login using factory

I am new to angularjs.I am using factories where i have written the fb login code.
And during the last step i am sending all the data to my server where the user is registered in my database and the token is sent.
Here is the code.
'use strict'
APP.factory('authenticationFactory',['ENV','$http','$rootScope', function (ENV,$http,$rootScope) {
return {
socialLogin:function(data){
return $http.post($rootScope.apiURL+'sociallogin',data).then(function (resp) {
if(resp.status == 200) {
return resp.data;
}
})
},
fbLogin: function () {
var FB = window.FB;
var scopes = 'public_profile,email';
var that = this;
FB.login(function (response) {
return that.facebookStatusChangeCallback(response);
}, {scope: scopes});
},
facebookStatusChangeCallback: function(response){
if (response.status === 'connected') {
// Logged into your app and Facebook.
var r = this.facebookApiRequest(response);
console.log(r);
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
console.log('Please log into this app.');
} else {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
console.log('Please log into Facebook.');
}
},
facebookApiRequest: function (authResponse) {
var that = this;
var r = FB.api('/me?fields=id,name,email,gender,first_name,last_name,age_range,link,birthday', function (response) {
var r = FB.api("/" + response.id + "/picture?height=720", function (pictureResponse) {
if (pictureResponse && !pictureResponse.error) {
/* handle the result */
response.profile_pic = pictureResponse.data.url;
response.access_token = authResponse.authResponse.accessToken;
response.provider = 'facebook';
response.devicetoken = '';
response.full_name = response.first_name+' '+response.last_name;
var r = that.socialPluginLogin(response).then(function (resp) {
return that.resp;
});
return r;
} else {
console.log('error while fatching fb pic');
}
});
console.log(r);
});
console.log(that);
},
socialPluginLogin : function (data) {
var resp = this.socialLogin(data).then(function (resp) {
return resp;
});
return resp;
}
};
}]);
I am calling the fbLogin() function from my controller. i need the response from the function socialLogin() so that i can change the state.
Where am i going wrong.??
The answer was pointing in the wrong direction, another try:
Your function fbLogin should return a promise, which can be resolved by socialLogin later. Since fbLogin doesn't return a thing, you don't receive any signal from the completed login.
See this:
// We add $q here
APP.factory('authenticationFactory',['ENV','$http','$rootScope','$q', function (ENV,$http,$rootScope,$q) {
var loginPromise;
return {
socialLogin:function(data){
return $http.post($rootScope.apiURL+'sociallogin',data).then(function (resp) {
if(resp.status == 200) {
// This is your connection to the controller
loginPromise.resolve(resp.data);
return resp.data;
}
})
},
fbLogin: function () {
var FB = window.FB;
var scopes = 'public_profile,email';
var that = this;
FB.login(function (response) {
return that.facebookStatusChangeCallback(response);
}, {scope: scopes});
// Create and return a promise
loginPromise = $q.defer();
// EDIT: My fault, return the promise:
return loginPromise.promise;
},
//...
And add this to the controller:
authenticationFactory.fbLogin().then(function(data){
// Check it out:
console.dir(data);
})
Additional things you should consider:
Define your functions in the function body, not in the return statement. You can eliminate that=this this way
Only return the API, not all the functions
Read up on promises, they are the way to go in the angular world. You might as well use callbacks, but those are tedious to handle.
Change your socialLogin function to below, your function would return a promise object which you can consume in socialPluginLogin via then which you are already doing.
socialLogin:function(data){
return $http.post($rootScope.apiURL+'sociallogin',data)
},

How to replicate jQuery ajax method

The problem: I'm trying to replicate the jQuery ajax method since I'm using XMLHttpRequest more than once in a script. However, I do not think including jQuery as a dependency is necessary since I would only be using a maximum of 3 methods from the jQuery library. Therefor I need a good way of replicating the jQuery's ajax method and so far I've gotten this far but please see explanation of output below the code example:
function ajax(obj) {
/*
obj = {
type: 'GET',
url: 'my/url/',
success: function (response) {},
error: function (response) {},
isTrue: true
}
*/
var
response = null, // defaults to null
complete = function (resp) {
console.log(resp); // outputs the response
response = resp;
},
error = function (resp) {
response = resp;
},
request = new XMLHttpRequest();
request.open(obj.type || 'GET', obj.url, obj.isTrue || true);
request.onreadystatechange = function (e) {
if (request.readyState === 4) {
if (request.status >= 200 && request.status < 400) {
complete(request.responseText);
} else {
error(request.statusText);
}
}
}
request.send();
return {
done: function (callback) {
callback(response);
}
}
}
Then when I call the ajax function in another function:
var xhr = ajax({
url: 'js/routes.js',
}).done(function (resp) {
console.log(resp); // outputs 'null'
});
the response variable is null although the complete() function set the response variable to the value of the ajax .responseText.
Question: How can I return the value of .responseText from the request to the object the ajax function is returning so that I can do something with it in a callback function like I intend to do inside the .done() method of that object?
Thank you!
You have an error in your implementation. The 'done' function does not wait for response.
function ajax(obj) {
/*
obj = {
type: 'GET',
url: 'my/url/',
success: function (response) {},
error: function (response) {},
isTrue: true
}
*/
var _callback = null,
response = null, // defaults to null
complete = function (resp) {
if(_callback){
_callback(resp);
}
response = resp;
},
error = function (resp) {
if(_callback){
_callback(resp);
}
response = resp;
},
request = new XMLHttpRequest();
request.open(obj.type || 'GET', obj.url, obj.isTrue || true);
request.onreadystatechange = function (e) {
if (request.readyState === 4) {
if (request.status >= 200 && request.status < 400) {
complete(request.responseText);
} else {
error(request.statusText);
}
}
}
request.send();
return {
done: function (callback) {
if(response){
callback(response);
}else{
_callback = callback;
}
}
}
}
EDIT*
consider using a microlibrary instead of jQuery. Don't reinvent the wheel.
http://microjs.com/#ajax

How to access $http.get caller variable

Consider this simple angularjs code:
$http.get( url ).then(function ( response ) {
var cache = new Cache(url);
cache.response = response;
});
My problem is the above code is nondeterministic. Sometime the url do not match when the response is get from the server.
I would like to edit 10 contact data simultanously.
So for that to work, I would like to cache the requests to the server and put it into a javascript object.
I have written a simple service to achieve that, but suffers from the above bug.
Here is the code:
angular.module('myApp')
.factory('save', function($http, $q) {
// Private object
var Cache = function(url) {
this._url = url;
this.response = {};
this.saveDeferred = null;
this.saveDeferredFulfilled = false;
};
Cache.prototype.$save = function () {
return $http.put( this._url ).then(function (response) {
this.response = response;
return response;
});
};
//public method
var draft = {
caches: {},
get: function ( url ) {
if (draft.caches.hasOwnProperty(url)) {
return draft.caches.url.response;
} else {
return $http.get( url ).then(function ( response ) {
var cache = new Cache(url);
cache.response = response;
return cache;
});
}
},
save: function(url) {
if (draft.caches.url.saveDeferred) {
if (!draft.caches.url.saveDeferredFulfilled) {
draft.caches.url.saveDeferred.reject(new Error('forced timeout'));
}
draft.caches.url.saveDeferred = null;
draft.caches.url.saveDeferredFulfilled = false;
}
draft.caches.url.saveDeferred = $q.defer();
draft.caches.url.response.version = (parseInt(draft.caches.url.response.version) + 1).toString();
$http.put(url, draft.caches.url.response)
.success(function(data) {
console.log('some data returned');
console.log(data);
draft.caches.url.saveDeferredFulfilled = true;
draft.saveDeferred.resolve(data);
})
.error(function(error) {
console.log('Some error occured in save.creates');
console.log(error);
draft.saveDeferred.reject(error);
});
return draft.saveDeferred.promise;
}
};
return draft;
});
It must be something really basic, what I'm missing here.

Backbone router using jQuery $.get() promise to determine logged in state of user not working as expected

I'm trying to use a jQuery promise to make authenticated.done wait until the $.get() in .isAuthenticated returns, but I'm not getting the result I was expecting... the function inside authenticated.done runs before the preceding $.get() returns and thus does not work. Am I doing something wrong or am I going about this in entirely the wrong way?
isAuthenticated : function() {
// make a request to the server and see if the response is a login form or not
// this should just return true or false, not actually handle login etc
var authenticated = false;
console.log("authenticating...");
var ready = Promise.from(null);
$.get("/loggedin")
.then(function(data, textStatus) {
var rtnVal = false;
if (textStatus == "success" && !(data instanceof Object)) {
console.log("failure returned");
} else {
console.log("success returned");
rtnVal = true;
}
return rtnVal;
})
.done(function(result) {
authenticated = result;
});
return ready.then(function () {
return authenticated;
})
},
render: function (view) {
if(this.currentView) this.currentView.destroy();
var authenticated = this.isAuthenticated();
authenticated.done(function (response) {
if (response == true) {
console.log("Authentication success!");
// set the currentView
this.currentView = view;
// render the new view
this.currentView.render();
// set the view's menu items
if (this.currentView.navLink !== undefined) {
$(this.currentView.navLink).addClass("active");
}
} else {
console.log("Authentication failed...");
view = new app.LoginView();
view.render();
this.currentView = view;
}
});
return this;
}
And the console output:
authenticating... router.js:45
Authentication failed... router.js:89
success returned router.js:55
Here's what your code should look like using jQuery's Deferred/Promise objects:
{
authenticate: function () {
var authentication = $.Deferred();
$.get("/loggedin")
.then(function (data, textStatus) {
if (textStatus === "success" && !(data instanceof Object)) {
authentication.resolve(data, textStatus);
} else {
authentication.reject(data, textStatus);
}
});
return authentication.promise();
},
render: function (view) {
if (this.currentView) this.currentView.destroy();
this.authenticate()
.done(function (data, textStatus) {
this.currentView = view;
this.currentView.render();
$(this.currentView.navLink).addClass("active");
})
.fail(function (data, textStatus) {
view = new app.LoginView();
view.render();
this.currentView = view;
});
return this;
}
};
Notes:
since then is called regardless of success or failure of the GET request you don't need a fail callback.
I've renamed the function to the more appropriate authenticate, because it is an action, not a state
jQuery does not care if you pass undefined to it, so your if (this.currentView.navLink !== undefined) check is superfluous
You might want to use data and textStatus in the authentication callbacks somehow. If you don't need them, call resolve() or reject() without arguments.
I do not know what is Promise object that you are using, but using standard jquery deferred object the code will look:
isAuthenticated : function() {
// make a request to the server and see if the response is a login form or not
// this should just return true or false, not actually handle login etc
var authenticated = $.Deferred();
console.log("authenticating...");
$.get("/loggedin")
.then(function(data, textStatus) {
if (textStatus == "success" && !(data instanceof Object)) {
console.log("failure returned");
authenticated.reject();
} else {
console.log("success returned");
authenticated.resolve();
}
}, function () {
authenticated.reject();
});
return authenticated;
},
render: function (view) {
if(this.currentView) this.currentView.destroy();
var authenticated = this.isAuthenticated();
authenticated.done(function (response) {
if (response == true) {
console.log("Authentication success!");
// set the currentView
this.currentView = view;
// render the new view
this.currentView.render();
// set the view's menu items
if (this.currentView.navLink !== undefined) {
$(this.currentView.navLink).addClass("active");
}
} else {
console.log("Authentication failed...");
view = new app.LoginView();
view.render();
this.currentView = view;
}
});
authenticated.fail(function () {console.log('failed')});
return this;
}

Categories

Resources