I'm not sure how use a promise to wait for google to return a id_token. I would then make an ajax request using that token. Currently, it just immediately performs the ajax request before it has the token.
<script>
function onSignIn(googleUser) {
id_token = googleUser.getAuthResponse().id_token;
}
var app = angular.module('myApp', ['ngDialog']);
app.controller('directory_controller', function($scope, $q, $http, ngDialog) {
$http({
headers: { "Content-Type": "application/x-www-form-urlencoded" },
url: "my_ajax.php",
method: "POST",
data: "gtoken=" + id_token
})
.then(function successCallback(response) {
console.log("success");
console.log(response);
}),
function(response) {
console.log("failure");
console.log(response);
}
});
</script>
<div ng-app='myApp'>
<div ng-controller='directory_controller'>
</div>
</div>
<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
Related
I am making a post request to an api with submit() function which is attached to a ng-click directive sending the data in JSON format, it returns this error.
It is running fine on postman so the error is on client side only.
Also the email and selectedIds variables are not empty.
Here is my controller file:
app.controller('categoryController', ['$scope', '$rootScope', '$sce', '$http', '$timeout','$window', function($scope, $rootScope, $sce, $http, $timeout, $window) {
$scope.allCategories = {};
$http({
method: 'GET',
url: 'http://qubuk.com:8081/api/v1/alltag'
})
.then(function (data) {
// console.log("DATA:" + JSON.stringify(data.data.categories[0].displayName));
// console.log("DATA category:" + JSON.stringify(data.data.categories));
$scope.allCategories = data.data.categories;
});
$scope.selectedIds = [];
$scope.change = function(category, active){
if(active){
$scope.selectedIds.push(category.id);
}else{
$scope.selectedIds.splice($scope.selectedIds.indexOf(category.id), 1);
}
// console.log("SELECTED IDS:" + $scope.selectedIds);
};
$scope.email = "faiz.krm#gmail.com"
console.log("email is "+ $scope.email);
$scope.submit = function () {
var tagsData = {"emailId": $scope.email,
"tagsId": $scope.selectedIds};
console.log("tagsData:" + JSON.stringify(tagsData));
$http({
method:'POST',
url: 'http://qubuk.com:8081/api/v1/user/update/tags',
data: tagsData
})
.then(function (data) {
console.log("Ids sent successfully!");
alert("successful");
$window.location.href = '/app/#/feed';
})
};
// console.log("amm Categories:" + JSON.stringify($scope.allCategories));
}]);
edit: the response is not a JSON object... it is a string. I do think error is due to this only... how can i resolve it on the front end...
Try to add:
headers : { 'Content-Type': 'application/x-www-form-urlencoded'}
to your request:
$http({
method:'POST',
url: 'http://qubuk.com:8081/api/v1/user/update/tags',
data: tagsData,
headers : { 'Content-Type': 'application/x-www-form-urlencoded'}
})
Alternately try to pass a stringify data:
$http({
method:'POST',
url: 'http://qubuk.com:8081/api/v1/user/update/tags',
data: JSON.stringify(tagsData),
headers: {'Content-Type': 'application/json'}
})
In my ui-bootstrap modal I have 3 modal-body div's.
<div class="modal-body" ng-show="$ctrl.selected.item == 'registration'">...</div>
<div class="modal-body" ng-show="$ctrl.selected.item == 'thanks'">...</div>
<div class="modal-body" ng-show="$ctrl.selected.item == 'error'">...</div>
By changing $ctrl.selected.item I change HTML inside my modal window. Now I need to change this variable(property of object indeed) inside a registerService which is injected do registerwindow' controller.
app.service('registerService', ['$http', 'localStorageService', function ($http, localStorageService) {
this.registerUser = function (registerInfo) {
$http({
url: 'http://localhost:3000/v1/sign_up',
headers: {
'Content-Type' : 'application/json'
},
method: 'POST',
data: {
email: registerInfo.email,
nick: registerInfo.nick,
password: registerInfo.password,
password_confirmation: registerInfo.password_confirmation
}
})
.then(function successCall(response) {
console.log('user added'); // delete it
$ctrl.selected.item = $ctrl.items[1];
}, function errorCall(respone) {
console.log('error callback register ');
console.log(respone.data);
$ctrl.selected.item = $ctrl.items[2];
})
};
}]);
This approach with $ctrl.selected.item = $ctrl.items[1]; doesn't work obviously.. How can I do this? I have no clue I need to do this asynchronously.
You could probably use Angular's $q service to handle this. The service's method would look like this:
this.registerUser = function (registerInfo) {
var deferred = $q.defer();
$http({
url: 'http://localhost:3000/v1/sign_up',
headers: {
'Content-Type' : 'application/json'
},
method: 'POST',
data: {
email: registerInfo.email,
nick: registerInfo.nick,
password: registerInfo.password,
password_confirmation: registerInfo.password_confirmation
}
})
.then(function successCall(response) {
console.log('user added'); // delete it
//$ctrl.selected.item = $ctrl.items[1];
deferred.resolve(); //Resolve the promise - success
}, function errorCall(respone) {
console.log('error callback register ');
console.log(respone.data);
//$ctrl.selected.item = $ctrl.items[2];
deferred.reject(); //Reject the promise - failure
});
return deferred.promise;
};
Remember to inject $q into your service!
Within your controller, you'd call your service method like so, then adjust the scope variable within the .then and .catch:
registerService.registerUser(registerInfo)
.then(function() {
$scope.selected.item = $scope.items[1];
//Not sure what your controller looks like, you may be using controllerAs, so this will be a bit different
})
.catch(function() {
$scope.selected.item = $scope.items[2];
});
My app goes into infinite loop while firing $http get method inside a function
In my controller I am using POST and getting data from API after authorization and displaying it.
var app = angular.module('myApp', []);
app.controller('ctrl1', function($scope, $http) {
$http({
url: 'url',
method: "POST",
data: 'postData',
headers: {
'Authorization': 'value'
}
})
.then(function(response) {
$scope.hotels = response.data;
});
$scope.imagePath = function(id) {
console.info(id);
if (id) {
$http({
method: 'GET',
url: 'url=' + id
})
.then(function(response) {
var imgdata = response.data;
console.info(imgdata);
var imgdata1 = imgdata.data.image_name;
return "url" + imgdata1;
});
}
};
});
In my img ng-src I have to call data from another API from the key exterior_image which I am passing in my function but it goes into an infinite loop. Also I know I have to use angular forEach in imgdata1.
<div ng-controller='ctrl1'>
<select ng-options='item as item.hotel_name for item in hotels.data' ng-model='hotel'></select>
<h1>{{hotel.hotel_name}}</h1>
<p>{{hotel.hotel_description}}</p>
<img ng-src="{{imagePath(hotel.exterior_image)}}">
</div>
Try this in your Controller:
var app = angular.module('myApp', []);
app.controller('ctrl1', function ($scope, $http) {
$scope.current_Hotel = {
hotel_name: "Default Value Here",
hotel_description: "Default Value Here",
exterior_image: "Default id here",
image_url: "Default url here"
};
$http({
url: 'url',
method: "POST",
data: 'postData',
headers: {
'Authorization': 'value'
}
}).then(function (response) {
$scope.hotels = response.data;
});
$scope.selectHotel = function () {
$http({
method: 'GET',
url: 'url=' + $scope.current_Hotel.exterior_image
}).then(function (response) {
var imgdata = response.data;
var imgdata1 = imgdata.data.image_name;
$scope.current_Hotel.image_url = "url" + imgdata1;
});
};
});
and this:
<div ng-controller='ctrl1'>
<select ng-options='item as item.hotel_name for item in hotels.data' ng-model='current_Hotel'></select>
<h1>{{current_Hotel.hotel_name}}</h1>
<p>{{current_Hotel.hotel_description}}</p>
<img ng-src="{{current_Hotel.image_url}}">
</div>
Hello i need to show the response from a website (200, 404, etc) using REST services.
i have created a partial code but i dont know how show the result
This is js
angular.module('demo', [])
.controller('Hello', function($scope, $http) {
$http ({
method: 'GET',
url: 'http:/www.google.com'
}).
then(function(response) {
$scope.greeting = response.data;
});
})
and this is html
<body>
<div ng-controller="Hello">
<p>Result = {{greeting.content}}</p>
</div>
</body>
</html>
Thanks for help.
You should really be putting your $http calls into a separate service and injecting that into the controller.
so something like this:
angular.module('demo')
.factory('greetingService', function($http) {
this.getGreeting = function() {
return $http ({
method: 'GET',
url: 'http:/www.google.com'
}).then(function(response) {
return response.data
});
}
};
Then inject the service into your controller and call greetingService.getGreeting and then set your $scope variable to the result.
Also make sure you have the proper headers in your request.
The response is a IHttpPromise<T> which extends IPromise<IHttpPromiseCallbackArg<T>>.
The interface for this looks like this:
interface IHttpPromiseCallbackArg<T> {
data?: T;
status?: number;
headers?: IHttpHeadersGetter;
config?: IRequestConfig;
statusText?: string;
}
So you can access what you need with:
response.status
With your code:
angular
.module('demo', [])
.controller('Hello', HelloController)
function HelloController($scope, $http) {
$http({
method: 'GET',
url: 'http://enable-cors.org'
})
.then(function(response) {
var text = "The status: " + response.status;
$scope.directResponse = response;
$scope.greeting = {content: text};
$scope.someVariable = text;
});
}
/*
var $http = angular.injector(["ng"]).get("$http");
$http.get("http://enable-cors.org/").then(function(response) {
console.log(response.status);
});
*/
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo" ng-controller="Hello">
<p>Status = {{directResponse.status}}</p>
<p>Result = {{greeting.content}}</p>
<p>Result = {{someVariable}}</p>
</div>
I am trying to send data from my Angular.js controller to Node.js backend. I succeeded in making a MongoDB entry when the request is raised.But the data is missing in the MongoDB entry. I am stuck and can't proceed with my app anymore. Can anyone give me a clear explanation why I am not able to send the form data to the Node.js.
I had put my schema of the data here:
var common = require('../common');
var inviteeSchema = common.Schema({
email: String
});
var Invite = common.conn.model('Invite', inviteeSchema);
module.exports = Invite;
I have enclosed the routing code here.
router.route('/addtoinvitelist').post(function (req, res, next) {
var invite =new Invite(req.body);
invite.save(function(err,email){
if(err) throw err;
res.json({message:"your mail id is stored in our database we will soon send you an invite"})
});
});
My HTML form goes here
<form action="#">
<div class="form-group">
<label for="subcribeNewsletter" class="control-label">INVITE FORM<br> <small>We are happy to invite you to medicoshere, So please enter your email ID in the below form.</small></label>
<div class="input-group input-group-in input-group-sm">
<div class="input-group-addon"><i class="fa fa-envelope text-belpet"></i></div>
<input class="form-control" id="subcribeNewsletter" placeholder="name#mail.com" ng-model="useremail" required>
<div class="input-group-btn">
<button type="submit" class="btn btn-default text-belpet" ng-click="AddToInviteList(useremail)"><strong>OK</strong></button>
</div>
</div>
</div><!-- /.form-group -->
</form><!-- /form -->
my angular service functions goes here
`this.AddToInviteList = function (email, cb) {
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}, // set the headers so angular passing info as form data (not request payload)
data:"email"
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
}`
Controller function is here
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.email = {};
$scope.AddToInviteList = function () {
UserServices.AddToInviteList($scope.email, function (dataresponse) {
console.log(dataresponse);
})
}
});
Pass email as json object { 'email' : email }.
Just try this code:
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data:{ 'email' : email }
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
Controller :
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.AddToInviteList = function () {
$scope.user = {
email : $scope.useremail
};
UserServices.AddToInviteList($scope.user, function (dataresponse) {
console.log(dataresponse);
})
}
});
In server side you can access the email by calling 'req.body.email'
Change your model name in HTML input element with email and send request as
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/json'
},
data:{ 'email' : email }
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
and get it at backend side as
req.body.email
I think that should work!
Update
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.AddToInviteList = function () {
UserServices.AddToInviteList($scope.email, function (dataresponse) {
console.log(dataresponse);
})
}