Code issue with AngularJS and JSON - javascript

I have a JSON source and want to get results from it with a post request.
When I test with POSTMAN extension in chorme it works really well. But when I do that with angularJS the page keep loading and chrome consoles shows errors.
My code is here:
angular.module('loginApp', []).controller('loginController', function ($scope, $http) {
$scope.userName = '';
$scope.userPass = '';
$scope.output = function () {
var params = JSON.stringify({
username: '******',
password: '******'
});
$http({url: "http://xx.xx.xx.xx/api/user/login.json",
method: 'POST',
data: params,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then(function (response) {
return response;
});
};
});
Any help would be appreciated :)

try this, and after post error if occured:
var LoginApp = angular.module('loginApp', []);
LoginApp.controller('loginController', function ($scope, $common) {
$scope.userName = '';
$scope.userPass = '';
$scope.output = function () {
var params = JSON.stringify({
username: '******',
password: '******'
});
$common.ajax("http://xx.xx.xx.xx/api/user/login.json", params, "POST").then(function (response) {
console.log(response);
return response;
});
};
});
LoginApp.factory("$common", function($http, $q) {
function ajax(url, param, method) {
var request = $http({
method: method,
url: url,
data:param
});
var promise = request.then(
function(response) {
return(response.data);
},
function(response) {
console.log("Ocurred error: " + response);
return($q.reject("Something went wrong"));
}
);
return promise;
}
return({
ajax:ajax
});
});

Try this:
$scope.output = function () {
var params = {
username: '******',
password: '******'
};
$http.post("http://xx.xx.xx.xx/api/user/login.json", params)
.then(function (response) {
return response;
});
};
Also you should move your http request to a service. It's a bad practice put it in a controller.

Related

AngularJS service that uses multiple $http.get

I'm trying to learn AngularJS and I have the following service that works, but I'm wondering if there's a better way of writing it that is simpler and involves less duplication of code. Can you think of anything?
The service:
app.service("myService", function ($http) {
this.callData1 = function () {
var url = myurl1;
function getData() {
return $http.get(url);
}
return {
getData: getData,
}
},
this.callData2 = function () {
var url = myurl2;
function getData() {
return $http.get(url);
}
return {
getData: getData,
}
},
this.callData3 = function () {
var url = myurl3;
function getData(var1, var2) {
return $http({
url: url,
method: "GET",
params: { var1: var1, var2: var2 }
});
}
return {
getData: getData,
}
}
});
My controller:
app.controller("myController", function ($scope, myService) {
myService.callData1().getData().then(function (response) {
$scope.var1 = response.data;
});
myService.callData2().getData().then(function (response) {
$scope.var2 = response.data;
});
var var1 = "something";
var var2 = "something else";
myService.callData3().getData(var1, var2).then(function (response) {
$scope.var3 = response.data;
});
});
You can generalize it as follows:
app.service("myService", function ($http) {
this.getData = function(url, method, params){
var httpParams = {
url: url,
method: method || "GET", // If method is skipped, use "GET" by default
params: params || {} // If no params are given, take {}
};
return $http.get(httpParams);
};
});
And in controller, you can use this service as follows:
app.controller("myController", function ($scope, myService) {
var url = "https://blahblah";
myService.getData(url).then(function (response) {
$scope.var1 = response.data;
});
var params = {var1: "something", var2: "something2"};
myService.getData(url, "POST", params).then(function (response) {
$scope.var1 = response.data;
});
});

Updating mongodb with angularjs and node

I need to update my mongodb using nodejs and angularjs on the front end. I have the below code but i get error like `TypeError: Cannot read property 'put' of undefined
My angularjs controller :
myApp.controller('userController', ['$scope', '$resource', 'AuthService','iden','$http', function ($scope, $resource, AuthService,iden,$http) {
console.log(usersOnline);
var Meetup = $resource('/api/user', {},{
query: {method: 'get', isArray: true}
});
$scope.users = [];
$scope.userss = [];
$scope.text='mikyas';
Meetup.query({text: usersOnline}).$promise.then(function (results) {
$scope.users = results;
}, function(error) {
// console.log(error);
$scope.meetups = [];
});
console.log(usersOnline);
function getUser(iden,$http) {
//return promise here
var Users = $resource('/api/users', {},{
query: {method: 'get', isArray: true}
});
$scope.usersOnline='a';
return Users.query({username: usersOnline}).$promise
//other code as is
}
$scope.id='cpasgrave';
$scope.lol=getUser();
$scope.lol.then(function(user,$http){
console.log(user[0]._id);
iden=user[0]._id;
$scope.userss = user;
console.log(iden);
$http.put('/api/updateUser' + user[0]._id, user[0]);
});
console.log(iden);
}]);
And my api on the server side :
*
module.exports.updateUser = function (req, res) {
var id = req.body.id;
User.findById(id, function(err, user) {
if (err) throw err;
// change the users location
user.auto = 'true';
// save the user
user.save(function(err) {
if (err) throw err;
console.log('User successfully updated!');
});
});
}
`
Remove the $http argument in your $scope.lol.then(function(user,$http) function.
$scope.lol.then(function(user){
console.log(user[0]._id);
iden=user[0]._id;
$scope.userss = user;
console.log(iden);
$http.put('/api/updateUser' + user[0]._id, user[0]);
});
Also, if you define getUser (iden, $http), make sure you put correct arguments when you call it...
$scope.id='cpasgrave';
$scope.lol=getUser(iden, $http);
try replacing this:
$http.put('/api/updateUser' + user[0]._id, user[0]);
});
with this:
$http({
method: 'PUT',
url: '/api/updateUser' + user[0]._id, user[0]
}).then(function successCallback(response) {
console.log('put success');
}, function errorCallback(response) {
console.log('put failed');
});

Javascript promise wait for AccessToken value

I got huge problem with understanding values i got function which getting array with access token and I passing this token to ajax url to get json data. I know I need to use there promise to run ajax after I get access token. Could you help me with this one ?
componentDidMount: function () {
var component = this;
var accessToken = getAccessToken();
$.ajax({
type: 'GET',
url: window.APIUrl +'services/?access_token=' + accessToken,
dataType: 'json',
success: function(response)
{
component.setState({
services : response
});
}
});
}
function getAccessToken(){
var client_id = '****',
client_key = '****',
$ = jQuery;
if(!window.accessToken){
$.ajax({
url : APIUrl + 'auth',
method : 'post',
data : {
'id' : client_id,
'key' : client_key
},
success: function(response){
if(typeof response.access_token != 'undefined'){
/*console.log(response);*/
window.accessToken = response.access_token;
return response.access_token;
}else{
return false;
}
}
});
}else{
return window.accessToken;
}
}
Make your function getAccessToken to return a promise
componentDidMount: function () {
var component = this;
getAccessToken()
.then(function(accessToken) {
var url = window.APIUrl +'services/?access_token=' + accessToken,
return $.getJSON(url)
})
.then(function(response) {
component.setState({
services: response
});
});
}
function getAccessToken(){
if(window.accessToken) {
return $.when(window.accessToken)
}
return $.ajax(...) // get access token from server
}
Try something like this
componentDidMount: function () {
var component = this;
getAccessToken().then(function(accessToken) {
$.ajax({
type: 'GET',
url: window.APIUrl +'services/?access_token=' + accessToken,
dataType: 'json',
success: function(response)
{
component.setState({ services : response });
}
});
})
}
function getAccessToken(){
var deferred = $.Deferred()
var client_id = '****',
client_key = '****',
$ = jQuery;
if(!window.accessToken){
$.ajax({
url : APIUrl + 'auth',
method : 'post',
data : {
'id' : client_id,
'key' : client_key
},
success: function(response){
if(typeof response.access_token != 'undefined'){
/*console.log(response);*/
window.accessToken = response.access_token;
deferred.resolve(window.accessToken)
} else {
deferred.reject()
}
}
});
} else {
deferred.resolve(window.accessToken)
}
return deferred.promise()
}

Making Sync calls using promises Angular JS factories

I am trying to make sync calls using a factory pattern.
$scope.doLogin = function (username, password, rememberme) {
appKeyService.makeCall().then(function (data) {
// data = JSON.stringify(data);
debugAlert("login controller app key service"+data);
var appkeyvalue = data.d.appkey;
sessionConfigurationService.setBasicToken(appkeyvalue);
loginService.makeCall(username, password, rememberme).then(function (accessTokenData) {
if (accessTokenData.access_token !== "")
{
sessionConfigurationService.setAccessTokenData(accessTokenData.access_token);
userPreferencesService.makeCall().then(function (userPreferencesData) {
if (userPreferencesData.d.userId !== "")
{
sessionConfigurationService.setUserPreferences(userPreferencesData.d);
// $window.location.href = '/base.html';
}
});
}
});
});
};
My appKeyService factory is
app.factory('appKeyService', function ($q, authenticatedServiceFactory, configurationService) {
var deffered = $q.defer();
var service = {};
service.makeCall = function () {
debugAlert("appKeyService async method request start");
authenticatedServiceFactory.makeCall("GET", configurationService.getAppKeyURL(), "", "").then(function (data) {
debugAlert("appKeyService async method response")
deffered.resolve(data);
});
return deffered.promise;
};
return service;
});
My authenticated service factory is
app.factory('authenticatedServiceFactory', function ($http, $q, sessionConfigurationService) {
var deffered = $q.defer();
var service = {};
service.makeCall = function (methodType, URL, data, authType) {
var headerValue = "";
if (authType === "Basic") {
headerValue = sessionConfigurationService.getBasicToken();
} else if (authType === "Bearer") {
headerValue = sessionConfigurationService.getBearerToken();
}
var config = {headers: {
'Authorization': headerValue,
'Accept': 'application/json;odata=verbose',
},
withCredentials: true,
async: false
};
if (methodType === "GET") {
$http.get(URL, data, config)
.then(function (getData) {
debugAlert("GET method response" + JSON.stringify(getData));
deffered.resolve(getData.data);
}, function (error) {
debugAlert("GET method response error" + JSON.stringify(error));
deffered.reject(error);
});
}
else if (methodType === "POST") {
$http.post(URL, data, config)
.then(function (putData) {
debugAlert("POST method response" + JSON.stringify(putData));
deffered.resolve(putData.data);
}, function (error) {
debugAlert("POST method response error" + JSON.stringify(error));
deffered.reject(error);
});
}
else if (methodType === "DELETE") {
$http.delete(URL, data, config)
.then(function (deleteData) {
debugAlert("DELETE method response" + JSON.stringify(deleteData));
deffered.resolve(deleteData.data);
}, function (error) {
debugAlert("DELETE method response error" + JSON.stringify(error));
deffered.reject(error);
});
}
else if (methodType === "PUT") {
$http.put(URL, config)
.then(function (putData) {
debugAlert("PUT method response" + JSON.stringify(putData));
deffered.resolve(putData.data);
}, function (error) {
debugAlert("PUT method response error" + JSON.stringify(error));
deffered.reject(error);
});
}
return deffered.promise;
};
return service;
});
But I don't see the service calls are made in sync. So the "then" part in the controller is not executing after we receive the response. Its executing one after the other. How can I make that happen.
#Frane Poljak
Thank you for your comment. I just brought
var deffered = $q.defer();
inside the makeCall method and its working as I wanted now. Thank you!
app.factory('appKeyService', function ($q, authenticatedServiceFactory, configurationService) {
var service = {};
service.makeCall = function () {
var deffered = $q.defer();
debugAlert("appKeyService async method request start");
authenticatedServiceFactory.makeCall("GET", configurationService.getAppKeyURL(), "", "").then(function (data) {
debugAlert("appKeyService async method response")
deffered.resolve(data);
});
return deffered.promise;
};
return service;
});

angular $http.get() not sending signal to server after $http.post

I started using angular a week ago and I have been banging me head trying to solve this problem. I have a service that wraps $http because multiple controllers call the same url. There is one page that has a lot of business logic on the server on a post so I want to call $route.reload(). It seems to work because after vm.saveItem() the controller is reinitialized, but the $http.get() never sends the signal to the server for the new data. What am I doing wrong?
myModule.factory("itemRepository", function ($http) {
var baseUrl = "/api/inventory";
return {
getLocations: function (itemName) {
return $http({
url: baseUrl + "/" + itemName + "/locators",
method: "GET",
cache: false
});
},
addNewLocator: function (itemName, newLocator) {
return $http.post(baseUrl + "/" + itemName + "/locators", newLocator);
}
};
});
// itemEditorController.js
(function () {
"use strict";
angular.module("app-inventoryitems")
.controller("itemEditorController", itemEditorController);
function itemEditorController($routeParams, $route, itemRepository) {
// initialize vars
var vm = this;
vm.itemName = $routeParams.itemName;
vm.errorMessage = "";
// Models
vm.items = [];
vm.isBusy = true;
vm.newLocator = {};
vm.newLocator.name = vm.itemName;
// PROBLEM HERE, does not call server after post new data
// and $route.reload() was called
itemRepository
.getLocations(vm.itemName)
.then(function (response) {
angular.copy(response.data, vm.items);
}, function (err) {
vm.errorMessage = "Failed to load batches.";
})
.finally(function () {
vm.isBusy = false;
});
vm.saveItem = function () {
vm.isBusy = true;
itemRepository.addNewLocator(vm.itemName, vm.newLocator)
.then(function (response) {
vm.newLocator = {};
$route.reload();
}, function (error) {
vm.errorMessage = "Failed to save new item.";
})
.finally(function () {
vm.isBusy = false;
})
}
}
})();
Try to add dynamic parameter to your request:
$http({
url: baseUrl + "/" + itemName + "/locators",
method: "GET",
cache: false,
params: {
r: Math.random().toString(16).substr(2)
}
});
If issue was solved, need looking for HTTP Caching policies.
Google for necessary server-side headers.

Categories