AngularJS + API call - javascript

Trying to understand how AngularJS works, doing my first API calls, when I got stuck.
I want to do 2 API calls, but I can't seem to make it work.
After the first $http.get I want to do an another call (using the information from the previous call) but that doesn't work for some reason. (I get no alert)
The city and country are working perfectly after the first .get
JS:
var app = angular.module('weather', []);
app.controller("weatherCtrl", function($scope, $http) {
$http.get("http://ipinfo.io/json").then(function(response) {
$scope.city = response.data.city;
$scope.country = response.data.country;
var apiKey = "";
var apiCall = "api.openweathermap.org/data/2.5/weather?q=" + response.data.city + "&APPID=" + apiKey;
$http.get(apiCall).then(function(responsew) {
// $scope.temperature would get a value here
alert("1")
});
});
})
HTML:
<body ng-app="weather" ng-controller="weatherCtrl">
<h1 class="text-center">Weather</h1>
<h2 class="text-center">{{city}}, {{country}}</h2>
<h2 class="text-center">{{temperature}} °C</h2>
</body>

You can use promise to call the request after another which is the recommended way to do,
Another thing is you are missing the http part in the second request
Code:
app.controller("weatherCtrl", function ($scope, $http) {
function infoReq() {
return $http({
method: 'Get',
url: 'http://ipinfo.io/json'
})
}
function weatherReq() {
var apiKey = "";
var apiCall = "http://api.openweathermap.org/data/2.5/weather?q=" + $scope.city + "&APPID=" + apiKey;
return $http({
method: 'Get',
url: apiCall,
})
}
$scope.makeRequest = function () {
infoReq()
.then(function (response) {
$scope.city = response.data.city;
$scope.country = response.data.country;
return weatherReq();
})
.then(function (response) {
console.log(response.data);
})
}
})

var req = {
method: 'POST',
url: "http://api.openweathermap.org/data/2.5/weather?q=" + $scope.city + "&APPID=" + apiKey;
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
You can use the above http service to make the request inside your angularjs controller.

Related

Convert JS Post Ajax to AngularJS Post Factory

I am trying to convert an Ajax call with WSSE authentication to an AngularJS factory.
The method is Post.
The intended use of this is to access the Adobe Analytics Rest API and return data to be converted to JSON and then visualised with d3.js.
I am not familiar with the properties that can be used in an AngularJS $http post call and so not sure what is the correct way to do the WSSE auth, dataType, callback etc.
This is the original ajax code which came from a public github repo:
(function($) {
window.MarketingCloud = {
env: {},
wsse: new Wsse(),
/** Make the api request */
/* callback should follow standard jQuery request format:
* function callback(data)
*/
makeRequest: function (username, secret, method, params, endpoint, callback)
{
var headers = MarketingCloud.wsse.generateAuth(username, secret);
var url = 'https://'+endpoint+'/admin/1.4/rest/?method='+method;
$.ajax(url, {
type:'POST',
data: params,
complete: callback,
dataType: "text",
headers: {
'X-WSSE': headers['X-WSSE']
}
});
}
};
})(jQuery);
This is the current way the code is being used with pure JS:
MarketingCloud.makeRequest(username, secret, method, params, endpoint, function(response) {
data = JSON.parse(response.responseText);
});
I want to convert this to a factory and a controller respectively.
This is what I have done for the factory so far:
app.factory('mainFactory', ['$http', function($http) {
var wsse = new Wsse ();
return function(username, secret, method, params, endpoint) {
return $http({
method: 'POST',
url: 'https://' + endpoint + '/admin/1.4/rest/?method=' + method,
data: params,
headers: {
'X-WSSE': wsse.generateAuth(username, secret)['X-WSSE']
},
dataType: 'text',
});
};
}]);
And this is what I have for the controller:
app.controller('mainController', ['$scope', 'mainFactory', function($scope, mainFactory) {
mainFactory.success(function(data) {
$scope.data = data;
});
}]);
Currently I get an error saying mainFactory.success is not a function which I assume is because the factory isn't working yet.
I have resolved this question myself. The parameters I was passing to the first function in the factory were globally defined already and therefore getting over-written.
The first function is not required anyway.
Here is the factory code:
app.factory('mainFactory', ['$http', function($http) {
var wsse = new Wsse ();
return {
getAnalytics : function (){
$http({
method: 'POST',
url: 'https://' + endpoint + '/admin/1.4/rest/?method=' + method,
data: params,
headers: {
'X-WSSE': wsse.generateAuth(username, secret)['X-WSSE']
}
})
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}
};
}]);
And here is the controller code:
app.controller('mainController', ['$scope', 'mainFactory', function($scope, mainFactory) {
$scope.title = "Inn Site";
$scope.data = mainFactory.getAnalytics();
}]);

Is there any better way to display POST request in Angular Js

I have used both PUT and POST request to modify and create a data. But the thing is POST request is not working properly. When i click on add() button , automatically POST request is generating id in the json-data before filling the information in the text fields.
Moreover data should be updated when I click on the save() button . Below I have pasted my code, if I have made any mistake tel me know and I appreciate every one whomever gives any information.
HTMl :
<button class="btn btn-info" ng-click="addmode()"> Add </button>
<button class="btn btn-success" ng-show="editMode" ng-click="saveinfo()"> Save </button>
Angular JS :
$scope.addmode = function(information) {
var postinfo = information;
$http({
url:'http://localhost:3000/contacts' ,
method : 'POST',
data : postinfo
})
.then(
function successCallback(response) {
$scope.selectedcontact = '';
console.log(response.data)
},
function errorCallback(response) {
console.log("Error : " + response.data);
});
};
First create services/api.js
angular.module('app')
.factory('api', function ($rootScope,ApiEndpoint, $http, $q,$timeout,$cookies) {
var get = function (url) {
var config = {url: url, method: ApiEndpoint.Methods.GET};
return this.call(config);
};
var del = function (url) {
var config = {url: url, method: ApiEndpoint.Methods.DELETE};
return this.call(config);
};
var post = function (url, data) {
var config = {url: url, method: ApiEndpoint.Methods.POST, data: data};
return this.call(config);
};
var put = function (url, data) {
var config = {url: url, method: ApiEndpoint.Methods.PUT, data: data};
return this.call(config);
};
return {call: call, get: get, post: post, del: del, put: put};
});
After create service/apiendpoint.js
angular.module('app')
.constant('ApiEndpoint', {
ServerUrl: 'http://localhost/',
BaseUrl: 'http://localhost/',
Methods: {GET: 'GET', POST: 'POST', PUT: 'PUT', DELETE: 'DELETE'},
Models: {
test:"fe_api/test",
},
URLS: {
QUERY: 'app/'
},
getUrl: function (url) {
var host=window.location.host;
var protocol=window.location.protocol ;
return protocol+"//"+host+"/"+url;
}
});
**Create model handler **
angular.module('app')
.factory('ApiService', function (api, ApiEndpoint) {
var getModel = function (url_part)
{
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + url_part;
return api.get(url);
};
var getModelViaPost = function (url_part, data)
{
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + url_part;
return api.post(url, data);
};
var postModel = function(model_name, data) {
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + model_name;
return api.post(url, data);
};
var putModel = function(model_name, data) {
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + model_name;
return api.put(url, data);
};
var deleteModel = function(model_name, id) {
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + model_name + '/' + id;
return api.delete(url);
};
return {
getModel: getModel,
postModel : postModel,
putModel : putModel,
deleteModel : deleteModel,
getModelViaPost : getModelViaPost
};
});
write API call in the controller
var data = {
wut_token: $cookies.data,
};
ApiService.postModel(ApiEndpoint.Models.test, data).then(function (response) {
if (response.SUCCESS == "FALSE") {
} else {
}
})

How to call nest factory in Angularjs?

Hi I am developing web application in angularjs. I have requirement below. I have one factory. I have added code snippet below.
myapp.factory('sadadpaymentapi', ['$http', '$cookieStore', 'cfg', 'ScrollFunction', 'leaselisting', function ($http, $cookieStore, cfg, ScrollFunction, leaselisting) {
var sadadpaymentapiobject = {};
var baseurl = cfg.Baseurl;
var LoginID = $cookieStore.get("LoginID");
var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
var urlapi = baseurl + "api/ServiceRequest/CreateRSSedad/";
sadadpaymentapiobject.callsadad = function (PaymentType) {
leaselisting.leaselisting().then(function (response) {
//Problem in calling
}, function (error) { });
var request = {
url: urlapi,
method: 'POST',
data: {
SRActivityID: LoginID,
PaymentType: PaymentType,
PaymentAmount: "100"
},
headers: ScrollFunction.getheaders()
};
return $http(request);
}
return sadadpaymentapiobject;
}]);
Here is my second factory leaselisting
myapp.factory('leaselisting', ['$http', '$cookieStore', 'cfg', 'ScrollFunction', function ($http, $cookieStore, cfg, ScrollFunction) {
var leaselistingobject = {};
var baseurl = cfg.Baseurl;
var LoginID = $cookieStore.get("LoginID");
var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
leaselistingobject.leaselisting=function(){
var requestObj = {
url: "api/ServiceRequest/GetROLSPSRLeaseList/",
data: {
LoginID: LoginID,
RSAccountNumber: $cookieStore.get("AccountNumber")
},
headers: ScrollFunction.getheaders()
};
$http(requestObj).then(function (response) {
}, function (error) {
});
}
return leaselistingobject;
}]);
I have found error in below line
leaselisting.leaselisting().then(function (response) { //Problem in calling
}, function (error) { });
May i am i doing anything wrong in the above code? May i know is it possible to call one factory from another? The response i get from leaselisting i want to pass it in callsadad function of sadadpaymentapi. So can someone hep me in the above code? I am getting error Cannot read property 'then' of undefined in the leaselisting.leaselisting().then(function (response) {},function(error){});
Also is there any way I can directly inject factory like payment amount: inject factory something like this?
I assume, that leaselistingobject.getValue is an asynchronous function.
So first of get your value :
leaselistingobject.getValue = function(){
var requestObj = {
url: "api/ServiceRequest/getValue/"
};
return $http(requestObj).then(function (response) {
return response.data;
});
}
And then use it. To let all async actions finish we use angulars $q.Here you can find a small tutorial.
myapp.factory('sadadpaymentapi', ['$http', '$cookieStore', 'cfg', 'ScrollFunction', 'leaselisting', '$q',function ($http, $cookieStore, cfg, ScrollFunction, leaselisting, $q) {
var sadadpaymentapiobject = {};
var baseurl = cfg.Baseurl;
var LoginID = $cookieStore.get("LoginID");
var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
var urlapi = baseurl + "api/ServiceRequest/CreateRSSedad/";
sadadpaymentapiobject.callsadad = function (PaymentType) {
var leastListingPromise = leaselisting.leaselisting();
var getValuePromise = leaselisting.getValue();
$q.all([leastListingPromise, getValuePromise]).then(function (responses) {
//Here you have both responses in an array
var request = {
url: urlapi,
method: 'POST',
data: {
SRActivityID: LoginID,
PaymentType: PaymentType,
PaymentAmount: responses[1]
},
headers: ScrollFunction.getheaders()
};
return $http(request);
});
}
return sadadpaymentapiobject;
}]);
To make leaselisting() return the response of the request change the end of the function from
$http(requestObj).then(function (response) {
}, function (error) {
});
to
return $http(requestObj).then(function (response) {
return response.data;
}, function (error) {
});
If wont do anything about possible errors you can omit the error function part:
return $http(requestObj).then(function (response) {
return response.data;
});

$http call to get data to other $http call in other file

I want to read URL from one json file and feed URL to other javascript file having $http GET request to execute that URL. I am using one service in another service file for getting data. Whenever I run it, it says undefined in url: property of bannerslides function.
common.js:
(function() {
angular.module('siteModule')
.service('loggerService', function($http, $q) {
var deffered = $q.defer();
$http.get('/config/config.json').then(function(data) {
deffered.resolve(data);
});
this.getPlayers = function() {
return deffered.promise;
}
})
})();
siteService.js:
(function() {
var confUrl;
angular.module('siteModule')
.service('siteService', function($http, $q, loggerService) {
this.bannerSlides = function() {
loggerService.getPlayers().then(function(data) {
confUrl = data.data.baseUrl + data.data.urls.site;
console.log("GOTURL", confUrl);
//move your return statement here
return $http({
method: "GET",
dataType: "json",
url: confUrl
})
});
}
})
})();
This error indicate that siteService.bannerSlides is not recognised as a promise. When i look at your code, you just return the actual value. Then what you need is callback in siteService.bannerSlides.
Error code is angular.js:14324 TypeError: Cannot read property 'then' of undefined
siteController.js
// modify this to accept callback instead of using then
siteService.bannerSlides(function (data) {
console.log(data);
})
siteService.js
this.bannerSlides = function(callback) {
loggerService.getPlayers().then(function(data) {
confUrl = data.data.baseUrl + data.data.urls.site;
console.log("GOTURL", confUrl);
//move your return statement here
$http({
method: "GET",
dataType: "json",
url: confUrl
}).then(function (response) {
// inspect/modify the received data and pass it onward
//console.log("MAke url", confUrl);
// add this
return callback(response.data);
}, function (error) {
// inspect/modify the data and throw a new error or return data
throw error;
});
}); //loggerService
}
Can you give an example on plunker/jsfiddle ?
You don't have to use deferred object and $q service with $http.
In loggerService you can just do
this.getPlayers = function() {
return $http.get('/config/config.json').then(function(data) {
return data;
});
}
Also, if you want to use then inside of siteController.js
siteService.bannerSlides().then
you are supposed to do a return inside bannerSlides functions, so it returns $http / promise.
On Jquery simple http GET jquery.getjson
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});

refresh an array without refreshing the page in angularJS

I have an array that I want to affect to it data that I have get from my Factory,but when I try to access it I don't get the data recently added to it,this the array when I try to fill it whith data:
$scope.copyofOpList = [];
$scope.UpdateOperations = function() {
$scope.copyofOpList = gammeOfFactory.getListOperations();
}
this is my Factory from which I get the Data:
.factory(
'gammeOfFactory',
function($http, $q) {
var backObject = {
getListOperations: _getListOperations
}
return backObject;
//used to get list of operations from ws
function _getListOperations() {
var defer = $q.defer();
$http({
method: "GET",
url: "MyWebService/getAll"
}).then(function mySucces(response) {
defer.resolve(response.data);
}, function myError(response) {
deferred.reject('Erreur into url ' + response);
});
return defer.promise;
};
});
so please,how can I refresh the Data in this array without refreshing the web page
thanks for help

Categories

Resources