Trouble getting json from API with angular - javascript

Trying to pull in some data using angular and an API. Obviously I'm quite new to this.
My custom service:
readIp.service('ip', ['$resource', function($resource){
this.getIP = function(ip) {
var ipData = $resource("http://www.telize.com/jsonip?callback=getip", {
callback : "JSON_CALLBACK"
}, {
get : {
method: "JSONP"
}
});
return ipData.get({ getip: ip });
}
}]);
From my controller:
$scope.getIP = ip.getIP($scope.getip);
HTML:
<strong>Your IP is:</strong> {{ getIP.ip }}
I'm getting an error currently:
Uncaught ReferenceError: getip is not defined
as the API shows up as: getip({"ip":"###.###.##.##"}); from the source.

Your service isn't properly defined. It should return an object that contains your getIp method. try something along the lines of :
readIp.factory('ip', ['$resource', function($resource){
return {
getIP: function(ip) {
// your code goes here
}
}
}]);

try this in place of above code. Hope you have already added ngResource module.
readIp.factory('ip',['$resource',function($resource){
return $resource('http://www.telize.com/jsonip?callback=getip', {}, {
query: {method:'GET', params:{}}
});
}])

Related

Angular1.6 Factory

Hii I m using following code. I am reading a json file name is "users.json". If i read this file in controller through $http everything works fine. but i want to use the data that i read from file, again and again in different controller so i made a factory for this. but in factory when i read data from that json file through $http.get() and in return when i call that service method in my controller and it returns Object { $$state: Object }
app.factory('AboutFactory',['$http',function ($http) {
return {
getter: function () {
return $http({
method : 'GET',
url : '/home/penguin/Modeles/users.json',
cache : true
})
.then(function (response) {
return response.data
})
}
}
}])
Result of getter function is a promise. so you should use it like this:
AboutFactory.getter().then(function(res)
{
console.log(res);
});
That's because the $http service returns a promise as mentioned in the documentation:
The $http API is based on the deferred/promise APIs exposed by the $q
service. While for simple usage patterns this doesn't matter much, for
advanced usage it is important to familiarize yourself with these APIs
and the guarantees they provide.
You can think of a promise as if you give a top secret message to someone to deliver personally to a friend, then when delivered, report back to you with a message back from your friend.
You provide the message (the request object) to the person so that they can attempt to make the delivery of the message (send the request).
The attempted delivery has taken place (the request has been sent), it either:
a) was delivered successfully (successful response) or
b) your friend was not in so the letter could not be delivered (non success response).
You can then act depending on the response you get back
a) Message was delivered (it was a successful request) and you got a letter back (do something with the response) or
b) Message failed to get delivered (request wasn't successful), so you can maybe try again later or do something else as you don't have the information you requested
Here is an example of using the $http service with the $q service:
// app.js
(function() {
'use strict';
angular.module('app', []);
})();
// main.controller.js
(function() {
'use strict';
angular.module('app').controller('MainController', MainController);
MainController.$inject = ['AboutFactory'];
function MainController(AboutFactory) {
var vm = this;
AboutFactory.getter().then(function(data) {
// do something with your data
vm.data = data;
}, function(error) {
// give the user feedback on the error
});
}
})();
// about.service.js
(function() {
'use strict';
angular.module('app').factory('AboutFactory', AboutFactory);
AboutFactory.$inject = ['$http', '$q']
function AboutFactory($http, $q) {
var service = {
getter: getter
};
return service;
function getter() {
// perform some asynchronous operation, resolve or reject the promise when appropriate.
return $q(function(resolve, reject) {
$http({
method: 'GET',
url: 'https://httpbin.org/get',
cache: true
}).then(function(response) {
// successful status code
// resolve the data from the response
return resolve(response.data);
}, function(error) {
// error
// handle the error somehow
// reject with the error
return reject(error);
});
});
}
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<div ng-app="app" ng-controller="MainController as MainCtrl">
<pre>{{MainCtrl.data | json}}</pre>
</div>
Try this approach. It will work as per your expectation.
Read JSON file in controller through $http service as it is works fine.
For sharing the response data from one controller to another you can create a service and store the data into that service.
Service :
app.service('setGetData', function() {
var data = '';
getData: function() { return data; },
setData: function(requestData) { data = requestData; }
});
Controllers :
app.controller('myCtrl1', ['setGetData',function(setGetData) {
// To set the data from the one controller
var data = 'Hello World !!';
setGetData.setData(data);
}]);
app.controller('myCtrl2', ['setGetData',function(setGetData) {
// To get the data from the another controller
var res = setGetData.getData();
console.log(res); // Hello World !!
}]);
Here, we can see that myCtrl1 is used for setting the data and myCtrl2 is used for getting the data. So, we can share the data from one controller to another controller like this.

AngularJS: Service call API and return JSON

I need to pass a value from an input field on the view using a service. The service should call my WebAPI2 and then receives an valid JSON as a response.
However, I am either getting an promise object, which I cannot resolve (even with ".then()"), or if I'm using an factory it won't compile as it seems to not implement the $get method.
The JSON Object I'm returning is also valid.
View :
<div class="input" ng-controller="InputController as ctrl">
<input ng-model="inputdata" /> {{inputdata}}
<button ng-click="ctrl.gibDaten(inputdata)">Senden</button>
{{cooledaten}}
</div>
Controller :
module GoogleMapsApp {
myApp.myAppModule.controller("InputController",
["$scope", "mapsServiceCustom",
function ($scope, mapsServiceCustom) {
$scope.lEingabedaten = $scope.inputdata;
this.gibDaten = function () {
$scope.cooledaten = mapsServiceCustom.gibDaten().then();
console.log($scope.cooledaten);
}
}]);
}
Service:
module GoogleMapsApp {
myApp.myAppModule.service("mapsServiceCustom",
["$http",
function ($http) {
this.gibDaten = function (lEingabe) {
console.log(lEingabe);
console.log($http.get("api/getDistanceData/" + lEingabe + "/Cologne")
.then(function(data) {
return data;
Controller:}));
return $http.get("api/getDistanceData/" + lEingabe + "/Cologne")
.then(function (data) {
return data;
});
//return $http.get("api/getDistanceData/" + lEingabedaten1 + "/Cologne");
}
}
]);
}
Console log:
Object { $$state: Object }maps.serviceCustom.js:14:17
Object { $$state: Object }InputController.js:8:17
If I check the $$state:Object it contains exactly the desired data.
Using a factory leads me to the following error:
https://docs.angularjs.org/error/$injector/undef?p0=mapsServiceCustom
So what am I doing wrong? How would I implement my intend?
You need to pass a function to then part...
So just put then function in your controller and set returning response to your variable...
myApp.myAppModule.controller("InputController",
["$scope", "mapsServiceCustom",
function ($scope, mapsServiceCustom) {
$scope.lEingabedaten = $scope.inputdata;
this.gibDaten = function () {
mapsServiceCustom.gibDaten().then(function(response){
// set response to your variable
$scope.cooledaten = response;
});
}
}]);
You have not implemented the service properly. please go through the following link (Angularjs official documentation)
https://docs.angularjs.org/guide/services
You need to expose your API by returning it an js object.(Same thing is shown in your error link. please refer to that as well)
module GoogleMapsApp {
myApp.myAppModule.service("mapsServiceCustom",
["$http", function ($http) {
this.gibDaten = function (lEingabe) {
console.log(lEingabe);
console.log($http.get("api/getDistanceData/" + lEingabe + "/Cologne")
.then(function(data) {
return data;
}
}
return { gibDaten: this.gibDaten};
}]);
}
Here You can learn more on $get
method https://docs.angularjs.org/guide/providers

Using $http in Angular Service - Cannot read property 'post' of undefined

I'm trying to learn how to use Angular right, by having all my business logic in services.
When I do a post request in a service, I get the following error:
Cannot read property 'post' of undefined
Here is some code:
UrlApp.controller('UrlFormCtrl', UrlFormCtrl);
UrlApp.factory('addUrlService', addUrlService);
function UrlFormCtrl($scope, $http) {
console.log('Url Form Controller Initialized');
$scope.addUrl = addUrlService.bind(null, $http);
}
function addUrlService($scope, $http){
console.log('initializing addUrlService');
return $http.post('urls/create', {'test':'test'}).then(function(response){
return response.data;
});
}
I'm just getting the hang of Angular, so I'm not entirely sure what I'm doing wrong. See any problems?
Firstly, you don't need to inject $scope in your service.
Secondly, you don't need to inject $http service in your controller.
Thirdly, you need to inject the service in your controller.
Finally, addUrlService service is returning a promise meaning it will make a request when service is instantiated. You may want to return a function instead or an object containing several functions.
So I would change your code to:
UrlApp.controller('UrlFormCtrl', UrlFormCtrl);
UrlApp.factory('AddUrlService', AddUrlService);
function UrlFormCtrl($scope, AddUrlService) {
$scope.addUrl = AddUrlService.addUrl;
}
function AddUrlService($http) {
function addUrl() {
return $http.post('urls/create', {
'test': 'test'
}).then(function (response) {
return response.data;
});
}
return {
addUrl: addUrl
};
}
Can you try like this
UrlApp.controller('UrlFormCtrl', UrlFormCtrl);
UrlApp.factory('addUrlService', addUrlService);
function UrlFormCtrl($scope,addUrlService) {
console.log('Url Form Controller Initialized');
$scope.addUrl = addUrlService;
}
function addUrlService($http){
console.log('initializing addUrlService');
return $http.post('urls/create', {'test':'test'}).then(function(response){
return response.data;
});
}

AngularJS Factory, Service and HTTP Usage

I am new to learning angular and having trouble understand some of the basics.
I have my controller line shown below:
$scope.test = fileLoader.loadFile();
And my factory service shown below:
angular.module('myWellnessTrackerApp')
.factory('fileLoader', function($http) {
return{
loadfile : function(fileLoc){
$http.get('data/sideEffects.json').success(function(data) {
// you can do some processing here
return data;
});
}
};
});
Which throws an error. But when my controller line is
$scope.test = fileLoader.data;
And my service is
angular.module('myWellnessTrackerApp')
.factory('fileLoader', function($http) {
var obj = {content:null};
$http.get('data/sideEffects.json').success(function(data) {
// you can do some processing here
obj.content = data;
});
return obj;
});
Which i don't understand and I would like to be able to understand how to make services in particularly a HTTP service wrapper for requesting a page or local file and having it returned.
Thanks
You can't just do
$scope.test = fileLoader.loadFile();
loadFile is an async call, and you can't return from that! You can use .then to continue the promise pattern. Your factory would change to:
loadFile : function(fileLoc){
return $http.get('data/sideEffects.json').then(function(result) {
// you can do some processing here
return result.data;
});
}
And your controller:
fileLoader.loadFile().then(function(data) {
$scope.test = data;
});

Another Error: [$resource:badcfg] in Angular webapp

I'm following a Tuts+ tutorial on building an AngularJS webapp. Everything went well untill I tried getting JSON data on the screen.
I keep getting the following Error: [$resource:badcfg]
Here's my code:
Service
angular.module('ContactsApp')
.factory('Contact', function ($resource) {
return $resource('/api/contact/:id', { id: '#id' }, {
'update': { method: 'PUT' }
});
})
Controller
angular.module('ContactsApp')
.controller('ListController', function($scope, Contact) {
$scope.contacts = Contact.query();
$scope.fields = [ 'firstName', 'lastName'];
$scope.sort = function(field){
$scope.sort.field = field;
$scope.sort.order = !$scope.sort.order;
};
$scope.sort.field = 'firstName';
$scope.sort.order = false;
});
I have allready searched the web for solutions and tried adding isArray:false to the declaration. I also compared all my code to the full code on GitHub, but I can't find the problem.
Did you try to pass an empty array when defining your module, like this :
angular.module('ContactsApp', [])

Categories

Resources