implementing the braintree-angular payment gateway with angular-fullstack generator [duplicate] - angularjs

This question already has answers here:
Why are AngularJS $http success/error methods deprecated? Removed from v1.6?
(2 answers)
Closed 3 years ago.
Getting this error:
angular.min.js:122 TypeError: $http.get(...).success is not a function
at getUserInfo (app.js:7)
at new (app.js:12)
at Object.invoke (angular.min.js:43)
at Q.instance (angular.min.js:93)
at p (angular.min.js:68)
at g (angular.min.js:60)
at g (angular.min.js:61)
at g (angular.min.js:61)
at angular.min.js:60
at angular.min.js:21
Here is my code:
var gitHub = angular.module('gitHub', []);
gitHub.controller('mainController', ['$scope', '$http', function($scope, $http) {
var $scope.user = '';
function getUserInfo($scope, $http){
$http.get('https://api.github.com/users')
.success(function (result) {
$scope.user = result;
console.log(result);
});
};
getUserInfo($scope, $http);
}]);
and here is the html
<!DOCTYPE html>
<html ng-app="gitHub">
<head>
<title>Github Users Directory</title>
<script src="angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="mainController">
<div>
<h1>GitHub Users</h1>
Who do you want to search for?<input type="text" name="FindHim" ng-model="queryName" />
<button ng-click="getUserInfo()">Search</button>
</div>
<div>
{{ user }}
</div>
</div>
</body>
</html>

The .success and .error methods are deprecated and have been removed from AngularJS 1.6. Use the standard .then method instead.
$http.get('https://api.github.com/users')
.then(function (response) {
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
$scope.user = data;
console.log(data);
});
Deprecation Notice
The $http legacy promise methods .success and .error have been deprecated and will be removed in v1.6.0. Use the standard .then method instead.
— AngularJS (v1.5) $http Service API Reference -- Deprecation Notice.
Also see SO: Why are angular $http success/error methods deprecated?.

i think you need to use .then and not .success when using angular.
Example from the doc's
var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
alert('Success: ' + greeting);
}, function(reason) {
alert('Failed: ' + reason);
}, function(update) {
alert('Got notification: ' + update);
});
Here is the example of how $Http uses it:
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
And finally your code could look like this
$scope.getUserInfo = function () {
$http.get('https://api.github.com/users')
.then(function (result) {
$scope.user = result;
console.log(result);
}, function(result) {
//some error
console.log(result);
});
};

this works
https://docs.angularjs.org/api/ng/service/$http
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

As per your current implementation, You are not passing arguments (i.e. $scope and $http) to getUserInfo from ng-click="getUserInfo()" thus you are getting the error.
You don't need to pass these as arguments as $scope and $http as its already injected in controller and define the function in $scope.
gitHub.controller('mainController', ['$scope', '$http', function($scope, $http) {
$scope.user = '';
//Redefined function, without arguments
$scope.getUserInfo = function (){
$http.get('https://api.github.com/users')
.success(function (result) {
$scope.user = result;
console.log(result);
});
};
$scope.getUserInfo();
}]);

You dont need to inject $scope, $http..
app.controller('MainController', function($scope, $http) {
$scope.fetchData = function(_city){
$http.get("../api/AllPlaces?filter[where][placeCity]="+ _city)
.then(function(response) {
$scope.Data = response.data;
});
}
});

No need to pass $http as a function parameter, since you have already injected $http as a dependency to your controller. I have made some modification to the code. Please check it will work fine for you.
var gitHub = angular.module('gitHub', []);
gitHub.controller('mainController', ['$scope', '$http', function ($scope, $http) {
$scope.user = '';
$scope.getUserInfo = function() {
$http.get('https://api.github.com/users')
.success(function (result) {
$scope.user = result;
console.log(result);
});
};
$scope.getUserInfo();
}]);

According to Angular JS $http documentation, this system has been excludede from 1.4.3 + So, I have taken help from his post and you can try this way
app.controller('MainCtrl', function ($scope, $http){
$http({
method: 'GET',
url: 'api/url-api'
}).then(function (success){
},function (error){
});
}
OR
$http.get('api/url-api').then(successCallback, errorCallback);
function successCallback(response){
//success code
}
function errorCallback(error){
//error code
}
I prefer the second one which was more flexible for me.

$http({
method: 'GET',
url: '....',
headers: {
'Authorization': 'Bearer ' + localStorage["token"]
}
})
.then(function (data, status, headers, config) {
alert(JSON.stringify(data) + "Status" + status);
})
.error(function (data, status, headers, config) {
alert(JSON.stringify(data) + "Status" + status);
});

function successCallback(response) {
return response
}
$http.get('url')
.then(successCallback)

Related

handle $http response angularjs - can't get value in console.log

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/

pass param to service from controller using typeahead in angularjs

Looking at this Plunker from an answer on SO
Plunker example
Learning angular and in the controller there is a param cityName, I am not sure how that works.
What I am trying to do is that I have a myController.js file
var app = angular.module("sampleApp");
app.controller('TypeaheadCtrl',['$scope','search', function ($scope, search) {
$scope.displayed=[];
search.getResult(searchQuery)
.then(function (data) {
$scope.displayed = (data.records);
});
}]);
myService.js
angular.module('sampleApp').factory('search', ['$q', '$http', function ($q, $http) {
var sdo = {
getResult: function (searchQuery) {
var promise = $http({
method: 'GET',
url: 'http://somewhere.com'
params: {
q: "a"
}
});
promise.success(function (data, status, headers, conf) {
return data;
});
return promise;
}
}
return sdo;
}]);
I want to be able to call the service after the third character is typed in the typeahead box and pass the characters to the service
You should use typeahead-min-length="3" option on typeahead input element.
HTML
<input type="text" ng-model="result"
typeahead="suggestion for suggestion in getSuggestion($viewValue)"
typeahead-min-length="3"/>
Then have function inside controller which will again return a promise.
$scope.getSuggestion = function (searchQuery){
return search.getResult(searchQuery)
.then(function (data) {
return data.records;
});
};
Since you have used .success the data will get return getResult function.
Use .then to chain promise so that you can return a data from the success callback.
Service
angular.module('sampleApp').factory('search', ['$q', '$http', function($q, $http) {
var sdo = {
getResult: function(searchQuery) {
var promise = $http({
method: 'GET',
url: 'http://somewhere.com'
params: {
q: searchQuery //<-- pass parameter here
}
});
promise.then(function(response) {
//you could format data here and returned formatted result
//or you could also do some sort of validation or filtering on data
return response.data;
});
return promise;
}
}
return sdo;
}]);
change your service like this
app.factory('search', ['$q', '$http', function($q, $http) {
var sdo = {};
sdo.getResult = function(query) {
var deferred = $q.defer();
var url = "http://someurlpath/api/" + query;
$http.get(url)
.success(function(data) {
deferred.resolve(data.data);
}).error(function(msg, code) {
deferred.reject(msg);
});
return deferred.promise;
};
return sdo;
}]);

Cannot set property from angularjs service

I am trying to set value in html page from angularjs controller.
I am getting value from web api in service but I have issue that I am always getting error:
TypeError: Cannot set property 'messageFromServer' of undefined
But I can't figure what am I doing wrong here. What am I missing?
On the html part I have:
<div ng-app="myApp" ng-controller="AngularController">
<p>{{messageFromServer}}</p>
</div>
In the controller I have:
var app = angular.module('myApp', []);
app.controller('AngularController', ['$scope', 'messageService', function ($scope, messageService) {
$scope.messageFromServer = "When I set it here it works!"
messageService.getMessage();
}]);
app.service('messageService', ['$http', function ($http) {
this.getMessage = function ($scope) {
return $http({
method: "GET",
url: "api/GetMessage",
headers: { 'Content-Type': 'application/json' }
}).success(function (data) {
$scope.messageFromServer = data;
console.log(data);
}).error(function (data) {
console.log(data);
})
};
}]);
Basically the problem is, you missed to $scope object to the service getMessage method. But this is not a good approach to go with. As service is singleton object, it shouldn't manipulate scope directly by passing $scope to it. Rather than make it as generic as possible and do return data from there.
Instead return promise/data from a service and then assign data to the scope from the controller .then function.
app.service('messageService', ['$http', function ($http) {
this.getMessage = function () {
return $http({
method: "GET",
url: "api/GetMessage",
headers: { 'Content-Type': 'application/json' }
}).then(function (response) {
//you could have do some data validation here
//on the basis of that data could be returned to the consumer method
//consumer method will have access only to the data of the request
//other information about request is hidden to consumer method like headers, status, etc.
console.log(response.data);
return response.data;
}, function (error) {
return error;
})
};
}]);
Controller
app.controller('AngularController', ['$scope', 'messageService',
function ($scope, messageService) {
$scope.messageFromServer = "When I set it here it works!"
messageService.getMessage().then(function(data){
$scope.messageFromServer = data;
});
}
]);
Don't use $scope in your service, just return the promise from $http.
var app = angular.module('myApp', []);
app.service('messageService', ['$http', function ($http) {
this.getMessage = function () {
return $http({
method: "GET",
url: "api/GetMessage",
headers: { 'Content-Type': 'application/json' }
});
};
}]);
app.controller('AngularController', ['$scope', 'messageService', function ($scope, messageService) {
messageService.getMessage().then(function(data) {
$scope.messageFromServer = data;
});
}]);
In this example you can unwrap the promise in your controller, or even better you can use the router to resolve the promise and have it injected into your controller.
app.config(function($routeProvider) {
$routeProvider.when('/',{
controller: 'AngularController',
templateUrl: 'views/view.html',
resolve: {
message: function(messageService) {
return messageService.getMessage();
}
}
});
});
Then in your AngularController, you'll have an unwrapped promise:
app.controller('AngularController', ['$scope', 'message', function ($scope, message) {
$scope.messageFromServer = message;
}]);

Angular Service - Pass $http data to scope

I´m trying to create an angular function inside on Service to return acess data via $http and then return to a desired scope.
So my service it something like this;
app.service('agrService', function ($http) {
this.testinho = function(){
return "teste";
}
this.bannerSlides = function(){
var dataUrl = "data/banner-rotator.json";
// Simple GET request example :
$http({
method: 'GET',
dataType: "json",
url: dataUrl
})
.success( function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
//console.log(data);
return data;
}).error( function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
alert("Niente, Nada, Caput");
});
}
})
Then i want to associate the returned data to a scope inside of my main App controller... like this:
app.controller('AppCtrl', function($scope, $http, agrService) {
$scope.slides = agrService.bannerSlides();
})
Then in my template i want to loop the data like this:
<div ng-repeat="slide in slides">
<div class="box" style="background: url('{{ slide.url }}') no-repeat center;"></div>
</div>
The problem is that the data it´s only available on success and i don´t know how to pass it to my scope slides!!!!!
What i´m doing wrong?
Many thanks in advance
bannerSlides() doesn't return the values you need right away. It returns a promise that you can use to obtain the value at a later time.
In your service you can use the .then() method of the promise that $http() produces to do initial handling of the result:
return $http({
method: 'GET',
dataType: "json",
url: dataUrl
}).then(function (data) {
// inspect/modify the received data and pass it onward
return data.data;
}, function (error) {
// inspect/modify the data and throw a new error or return data
throw error;
});
and then you can do this in your controller:
app.controller('AppCtrl', function($scope, $http, agrService) {
agrService.bannerSlides().then(function (data) {
$scope.slides = data;
});
})
Use this in your service
....
this.bannerSlides = function(){
var dataUrl = "data/banner-rotator.json";
return $http({
method: 'GET',
dataType: "json",
url: dataUrl
});
};
...
And this in your controller
agrService.bannerSlides().then(function(data) {
$scope.slides = data;
}, function() {
//error
});
you don't need $q promise inside the service because the $http is returning a promise by default
The $http service is a function which takes a single argument — a configuration object — that is
used to generate an HTTP request and returns a promise with two $http specific methods: success and error
reference
here is a Fiddle Demo
You need to return a promise and update your scope in the callback:
app.service('agrService', function ($q, $http) {
this.bannerSlides = function(){
var ret = $q.defer();
var dataUrl = "data/banner-rotator.json";
// Simple GET request example :
$http({
method: 'GET',
dataType: "json",
url: dataUrl
})
.success( function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
ret.resolve(data);
}).error( function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
ret.reject("Niente, Nada, Caput");
});
return ret.promise;
}
})
app.controller('AppCtrl', function($scope, $http, agrService) {
$scope.slides = null;
agrService.bannerSlides().then(function(data){
$scope.slides = data;
}, function(error){
// do something else
});
})
You can't return a regular variable from an async call because by the time this success block is excuted the function already finished it's iteration.
You need to return a promise object (as a guide line, and preffered do it from a service).
Following angular's doc for $q and $http you can build yourself a template for async calls handling.
The template should be something like that:
angular.module('mymodule').factory('MyAsyncService', function($q, http) {
var service = {
getData: function() {
var params ={};
var deferObject = $q.defer();
params.nameId = 1;
$http.get('/data', params).success(function(data) {
deferObject.resolve(data)
}).error(function(error) {
deferObject.reject(error)
});
return $q.promise;
}
}
});
angular.module('mymodule').controller('MyGettingNameCtrl', ['$scope', 'MyAsyncService', function ($scope, MyAsyncService) {
$scope.getData= function() {
MyAsyncService.getData().then(function(data) {
//do something with data
}, function(error) {
//Error
})
}
}]);

AngularJS : service not returning value

I'm trying to write an Angular service and it seems like there is something missing. My problem is its not returning any value to my Angular controller
getPrepTimes() method is not returning the http data
But when I check the network (via Chrome dev tools) it will correctly call the external api and return a json object as a response
#my service
'use strict';
angular.module('recipeapp')
.service('prepTimeService',['$http', function($http){
this.prepTime = getPrepTimes();
function getPrepTimes(){
$http({
url: '/prep_times/index.json',
method: 'GET'
})
.success(function (data, status, header, config){
return data;
});
};
}
]);
#controller
'use strict';
angular.module('recipeapp')
.controller('recipeCtrl', ['$scope', 'prepTimeService', function($scope, prepTimeService){
$scope.prep_time = prepTimeService.prepTime;
}]);
When I checked the method getPrepTimes() with returning a string it works. What could be missing here?
A couple things are wrong with the above. You assign this.prepTime to getPrepTimes(). The () there will invoke getPrepTimes immediately, and not when you actually call it! You also need to utilize callbacks to get your data back and use it:
angular.module('recipeapp').service('prepTimeService',['$http', function($http){
this.prepTime = getPrepTimes;
function getPrepTimes(callback) {
$http({
url: '/prep_times/index.json',
method: 'GET'
}).success(function (data, status, header, config){
callback(data);
});
};
}]);
And now use it like so:
prepTimeService.prepTime(function(data) {
$scope.prep_time = data;
});
Calls to the $http service are async, which means you need to return a promise (and not a value):
this.prepTime = function() {
return $http({
url: '/prep_times/index.json',
method: 'GET'
});
};
And on the controller:
angular.module('recipeapp')
.controller('recipeCtrl', ['$scope', 'prepTimeService', function($scope, prepTimeService){
$scope.prep_time = prepTimeService.prepTime()
.success(function (data, status, header, config){
$scope.someVar = data;
});
}]);
Wrap answer with promise:
var self = this;
var deferred = $q.defer();
self.getPrepTimes = function() {
$http({
url: '/prep_times/index.json',
method: 'GET'
})
.success(function(data, status, headers, config) {
if (data.error === undefined) {
deferred.resolve(data);
} else {
if (data.error !== undefined) {
} else {
deferred.reject(data);
}
}
}).error(function(data, status, headers, config) {
deferred.reject(data);
});
return deferred.promise;
};
In controller call it:
prepTimeService.getPrepTimes().then(function(result) {
$scope.prep_time = result;
},
function(error) {
// show alert
});

Resources