I am calling a json in controller using service but I am receiving an error saying "TypeError: Cannot read property 'then' of undefined". I tried existing answers but couldn't get it to work.
Controller:
app.controller("myController",["$scope","MyService","$http", function($scope,MyService,$http){
$scope.hi = "hello";
MyService.getMyData().then(function(response){
console.log(response);
});
}]);
Service:
app.service("MyService", ["$http", function($http) {
this.getMyData = function() {
return
$http({
method: 'GET',
url: 'myList.json',
headers: {
'Content-Type': 'application/json'
}
}).then(function successCallback(response) {
console.log(response);
return response;
}, function errorCallback(response) {
console.log(error);
return response;
});
};
}]);
Thank you.
Currently you had just return(on first line) thereafter on next line you returned $http promise. Basically you have return alone it returns nothing/undefined (this is how javascript works) & next statements are getting ignored from this.getMyData function.
You have to have return & $http({ promise to be together in one line, otherwise return will return empty statement.
this.getMyData = function() {
//`return` & `$http` promise should be on same line, otherwise undefined would get return
return $http({
method: 'GET',
url: 'myList.json',
headers: {
'Content-Type': 'application/json'
}
}).then(function successCallback(response) {
console.log(response);
return response;
}, function errorCallback(response) {
console.log(error);
return response;
});
};
#pankajparker is absolutely correct.
Implemented a codepen for kicks and adjusted to use Angular 1.5's components. Here's the link:
http://codepen.io/Lethargicgeek/pen/YWryoE
(function() {
angular.module("myApp", []);
angular.module("myApp").component('myCmp', {
controller: ctrlFn,
templateUrl: "myCmp.tpl.html"
});
ctrlFn.$inject = ["myService"];
function ctrlFn(myService) {
var $ctrl = this;
// BINDINGS
$ctrl.hi = "hello";
$ctrl.getData = getData;
$ctrl.data = null;
$ctrl.myService = myService; // Binding so that we can easily see results
// END BINDINGS
// FUNCTION
function getData() {
var returnedPrms = myService.getMyData();
returnedPrms.then(function(response) {
$ctrl.data = response;
});
}
// END FUNCTIONS
}
angular.module("myApp").service("myService", svcFn);
svcFn.$inject = ["$http"];
function svcFn($http) {
var svc = this;
//BINDINGS
svc.getMyData = getMyData;
//END BINDINGS
function getMyData() {
var firstPrms = $http.get("http://codepen.io/anon/pen/LVEwdw.js"); // Random bit of json pulled from internets
var secondPrms = firstPrms.then(function success(response) {
svc.successResp = response;
return response;
}, function error(response) {
svc.errorResp = response;
return response;
});
return secondPrms;
}
}
})(); // end iife
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.min.js"></script>
<div ng-app="myApp">
<script type="text/ng-template" id="myCmp.tpl.html">
<div>
<h1>{{$ctrl.hi}}</h1>
<a class="btn btn-primary" ng-click="$ctrl.getData()">
Trigger $Http Call
</a>
<dl class="dl-horizontal">
<dt>$ctrl.data:</dt>
<dd>{{$ctrl.data}}</dd>
<dt>$ctrl.myService.successResp:</dt>
<dd>{{$ctrl.myService.successResp}}</dd>
<dt>ctrl.myService.errorResp:</dt>
<dd>{{ctrl.myService.errorResp}}</dd>
</dl>
</div>
</script>
<my-cmp></my-cmp>
</div>
Related
I have been trying all and nothing. I wanted create simple circle slider from values with my service, but $scope.value didn't update my view. Take a look at my demo:
https://jsfiddle.net/gh42tqxs/11/
<div ng-app="mainApp">
<div ng-controller="FooController">
<ui-knob value="value" options="options" knob-format data-note="{{note}}"></ui-knob>
</div>
</div>
var app = angular.module("mainApp",['ui.knob']);
app.service('Service', function ($http, $q) {
this.Get = function (premiereId) {
var deferred = $q.defer();
var req = {
method: 'GET',
url: 'https://api.myjson.com/bins/63xhr',
headers: {
'Content-Type': 'application/json'
}
}
$http(req).then(function (response) {
if (response.status == 200) {
deferred.resolve(response.data);
}
else {
deferred.reject(response.data);
}
}, function (error) {
deferred.reject(error.data);
});
return deferred.promise;
}
})
app.controller("FooController", function (Service, $timeout, $scope) {
function test() {
Service.Get().then(function (response) {
$timeout(function () {
console.log(response);
$scope.value = response.Number;
$scope.options.min = response.NumberMin;
$scope.options.max = response.NumberMax;
}, 1000);
})
}
test();
});
Animation isn't starting, we start with the minimum value, not from $scope.value.
ng knob == jquery knob slider
How fix it? Please help me.
i want to use my controller for getting images link of dog with an api but I am not able to use the result.
var images = function(breed) {
var promise = $http({
method: 'GET',
url: 'https://dog.ceo/api/breed/' + breed + '/images/random'
})
.then(function successCallback(response) {
return response.data.message;
},
function errorCallback(response) {
});
return promise;
}
console.log(images("kelpie"));
the problem is, i can't get the link in the object.
if I change response.data.message by only response.data, this is why i get
when I add console.log(response.data) before the return, this is what I get:
If I try JSON.parse(response.data), I got this:
Do you know how to do ?
Thank you for your help
What you are seeing in the console is the promise itself.
if you want to view the value (which in this case will be the url) then do it like this
console.log(images("kelpie").value);
If you want to see the response data then you need to add the console.log() in the then() callback.
Do it like this:
.then(function successCallback(response) {
console.log(response.data.message);
return response.data.message;
}
can you try one with JSON.parse(response.data) and then fetch message property from it.
You need to utilize promise here.
One way to do this is -
angular.module('demo', [])
.controller('myController', ['$scope', 'demoService', function($scope, demoService){
demoService.test().then(function(response) {
$scope.url = response;
})
}])
.factory('demoService', ['$http', '$q',
function($http, $q) {
var demoService = {};
demoService.test = function() {
var deferred = $q.defer();
$http.get('https://jsonplaceholder.typicode.com/posts/1').then(
function(response) {
response = "https://www.w3schools.com/bootstrap/paris.jpg";
deferred.resolve(response);
}, function(error) {
console.log("some error occur");
console.log(error);
deferred.reject(error);
}
)
return deferred.promise;
}
return demoService;
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo" ng-controller="myController">
<img ng-src="{{url}}" />
</div>
Use promise deffer object
Refference - https://docs.angularjs.org/api/ng/service/$q
JS fiddle working code - https://jsfiddle.net/Shubhamtri/9y9ezkdt/1/
Please note that I already read all the StackOverflow questions that are somewhat related to my questions but none of these really answer my question. Please don't mark this as duplicate without fully understanding my question.
Here's my concern:
I would like to delay angularJS $http.get call without affecting the angular promise. Right now the code below throws a "angular-1.3.15.js:11655 TypeError: Cannot read property 'then' of undefined" in this line:
updatedPromise = promise.then(function(price)
Here's my partial code:
MyAPP.service('FirstService', ['$q','$http', 'Constants', 'SecondService', 'UtilityService', function($q, $http, Constants, SecondService, UtilityService) {
var self = this;
var processFunction = function(AnArray) {
var updatedPromise;
var promises=[];
angular.forEach(AnArray, function(itemObj, index)
{
var totalWorth = "";
if(itemObj.name != "")
{
var promise = SecondService.getPrice(itemObj.name);
updatedPromise = promise.then(function(price){
itemObj.price = price;
return itemObj;
}, function(error){
console.log('[+] Retrieving price has an error: ', error);
});
promises.push(updatedPromise);
}
else
{
console.log("Error!");
}
});
return $q.all(promises);
};
);
MyAPP.service('SecondService', ['$timeout','$http', 'Constants', function($timeout, $http, Constants) {
var self = this;
var URL = "/getPrice";
self.getPrice = function(itemName){
$timeout(function(){
var promise;
promise = $http({
url: URL,
method: 'POST',
data: {_itemName : itemName},
headers: {'Content-Type': 'application/json'}
}).then(function(response) {
return response.data;
}, function(response) {
console.log("Response: " + response.data);
return response.data;
});
return promise;
}, 3500);
console.log("[-]getPrice");
};
}]);
Please note that the processFunction should really return an array of promises because this is needed in other functions.
Your help will be highly appreciated!
Let me know for further questions/clarifications.
Thanks!
$timeout returns a promise, so you can return that, and then return the promise from $http:
self.getPrice = function (itemName) {
return $timeout(3500).then(function () {
return $http({
url: URL,
method: 'POST',
data: { _itemName: itemName },
headers: { 'Content-Type': 'application/json' }
});
}).then(function (response) {
return response.data;
}, function (response) {
console.log("Response: " + response.data);
return response.data;
});
};
How can i make the testservice factory return the result from the post request?, or make the app, factory update some $scope details thats within the overallcontroller ?
how can i update information within the overallcontroller from another controller?
app.factory('testservice', ['$http', 'auth', function($http, auth) {
var o = {
posts : []
};
o.test = function() {
return $http.post('/poster', null, {
headers: {Authorization: 'Bearer '+auth.getToken()}
}).success(function(data){
console.log(Data);
});
};
return o;
}]);
app.controller('overallController', ['$scope', 'posts', 'testservice', 'auth','$interval',
function($scope, posts, testservice, auth, $interval) {
$scope.data = {cash:"12879999",location:"test2",gang:"None","username":"test",
xp: 1290,
health: 100,
wanted: 30,
energy: 90};
var databackground = function() {
console.log("logging...");
var t = testservice.test;
console.log(t);
}
databackground();
$interval(databackground, 30000);
}]);
example html
<div class="main" ng-controller="overallController">
<section class="sides left" style="background:blue; height:100px;">
<ul>
<li ng-hide="isLoggedIn()">Logg inn</li>
</ul>
</section>
<div ng-controller"othercontroller">
// call made from some code here
</div>
</div>
Change your service to
o.test = function() {
return $http.post('/poster', null, {
headers: {Authorization: 'Bearer '+auth.getToken()}
}).then(function(response){
return response.data;
});
};
And in your controller, do call the service, and get the results back in the promise:
testservice.test().then(function(data) {
$scope.data = data;
});
Read more about how to use promises here
You return the promise from your service, you would listen for that to resovle and get hold of your data.
Using $rootScope is heavy handed approach and should be used as a last resort. Services and event are preferable.
var databackground = function() {
console.log("logging...");
testservice.test()
.then(function (res) {
console.log(res.data); //Here is your data
});
}
EDIT: Your service should change slightly also. Firstly .success and .error are deprecated. Use .then and .catch instead.
If you wish to just return data out of your service just do:
o.test = function() {
return $http.post('/poster', null, {
headers: {
Authorization: 'Bearer ' + auth.getToken()
}
});
};
However if you want to transform the data in your service you can but ensure your return it or your controller wont get anything:
o.test = function() {
return $http.post('/poster', null, {
headers: {
Authorization: 'Bearer ' + auth.getToken()
}
})
.then(function (res) {
res.data.test = 'lol';
return res;
})
};
Try referencing $rootScope instead of $scope.
This will allow controllers and factories to interact with each other.
angular.module('alertApp', [
'alertApp.controllers',
'alertApp.services'
]);
angular.module('alertApp.services', []).
factory('alertAPIservice', function($http) {
var alertAPI = {};
alertAPI.getAlerts = function() {
return $http({
method: 'JSONP',
url: 'http://localhost:50828/api/alert'
});
}
return alertAPI;
});
angular.module('alertApp.controllers', [])
.controller('mainController', function($scope, alertAPIservice) {
$scope.message = 'Hello Mid-World!';
$scope.alertsList = [];
alertAPIservice.getAlerts().success(function (response) {
$scope.alertsList = response;
});
});
My app runs fine without errors and I can see the $scope.message displayed on the page. In fiddler I can see that my api call returns a 200 message, but the success function is never called. What have I done wrong
UPDATE
I Changed to:
alertAPIservice.getAlerts().then(function successCallback(response) {
$scope.alertsList = response;
}, function errorCallback(response) {
console.log("turd");
});
And although I receieve a 200 in fiddler, the error callback is called. The response is from web api and is of type Ok();
You need to use the name of the callback as "JSON_CALLBACK".
Please refer your updated code as below -
angular.module('alertApp', ['alertApp.controllers','alertApp.services']);
angular.module('alertApp.services', []).factory('alertAPIservice', function($http) {
var alertAPI = {};
alertAPI.getAlerts = function() {
return $http.jsonp('https://angularjs.org/greet.php?name=StackOverflow&callback=JSON_CALLBACK');
//use &callback=JSON_CALLBACK' in url
}
return alertAPI;
});
angular.module('alertApp.controllers', [])
.controller('mainController', function($scope, alertAPIservice) {
$scope.message = 'Hello Mid-World!';
$scope.alertsList = "loading data";
alertAPIservice.getAlerts().then(function (response) {
$scope.alertsList = response.data;
},function(error,a,b){
$scope.alertsList = error;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="alertApp">
<div ng-controller="mainController">
{{message}}
<div>
<pre>{{alertsList|json}}</pre>
</div>
</div>
</body>
you can refer jsonp documentation here.
Hope this helps you!
Try this one ('then' instead of 'success' ):
alertAPIservice.getAlerts().then(function (response) {
$scope.alertsList = response;
});