When I log the id it shows me the correct id. I want to pass this id in the second url and fetch data accordingly.
Like when the id is 9 and when i put it like this url: &room_type=9&day=1 it works but not when I use it this way url: '&room_type=' +$scope.id + '&day=1'
$http({
method:'GET',
url: '&hotel_id=' +$scope.current_Hotel.hotel_id
}).then(function(response){
var roomdata = response.data;
$scope.roomdata = roomdata;
var roomtype = roomdata.data;
angular.forEach(roomtype, function(value, key){
var id = value.room_type_id;
$scope.id = id;
console.info(id);
});
});
$http({
method:'GET',
url: '&room_type=' +$scope.id + '&day=1'
}).then(function(response){
var plan = response.data;
$scope.plan = plan;
});
Its because the way async programming works in javascript. In your code you are calling these 2 http calls back to back and the defined callback (then) does not fire until later when you get a result. So id will not be populated at the time your 2nd http call is fired. If you want to call this with id and id is defined in the callback of your 1st call then you have to call it from inside the callback of your first http call, not after it.
Here is how you could handle it
$http({
method:'GET',
url: '&hotel_id=' +$scope.current_Hotel.hotel_id
}).then(function(response){
var roomdata = response.data;
$scope.roomdata = roomdata;
var roomtype = roomdata.data;
angular.forEach(roomtype, function(value, key){
var id = value.room_type_id;
$scope.id = id;
console.info(id);
});
// call http now that id is defined
$http({
method:'GET',
url: '&room_type=' +$scope.id + '&day=1'
}).then(function(response2){
var plan = response2.data;
$scope.plan = plan;
});
});
Http request you make works async, use promise chains to call the request after another
function getHotelId(){
return $http({
method:'GET',
url: '&hotel_id=' +$scope.current_Hotel.hotel_id
})
}
function getPlan(){
return $http({
method:'GET',
url: '&room_type=' +$scope.id + '&day=1',
})
}
$scope.processform = function() {
getHotelId()
.then( function( response )
{
var roomdata = response.data;
$scope.roomdata = roomdata;
var roomtype = roomdata.data;
angular.forEach(roomtype, function(value, key){
var id = value.room_type_id;
$scope.id = id;
console.info(id);
});
return getPlan();
})
.then(function(response){
console.log(response.data);
})
}
Related
How to pass the multiple parameters to a function using this code? I am able to pass only Username as single parameter but MarkDate is not passing to URL.
var app = angular.module("myModule", ['angularUtils.directives.dirPagination']);
//This Gets all the Pre Clients
app.controller("GetAttendance", function ($scope, $http) {
window.params = function () {
var params = {};
var param_array = window.location.href.split('?')[1].split('&');
for (var i in param_array) {
x = param_array[i].split('=');
params[x[0]] = x[1];
}
return params;
} ();
$http({
url: "../assets/services/MasterWebService.asmx/spGetAttendanceByUsernameDate",
method: "GET",
**params: { Username: window.params.Username , MarkDate : params.Markdate}**
}).then(function (response) {
console.log(response.data);
$scope.GetAttendanceData = response.data;
$scope.TotalOrders = response.data.length;
});
Your "MarkDate" param is not getting its value from the window.params object as you do with "Username". This should work:
$http({
url: "../assets/services/MasterWebService.asmx/spGetAttendanceByUsernameDate",
method: "GET",
**params: { Username: window.params.Username , MarkDate : window.params.Markdate}**
}).then(function (response) {
console.log(response.data);
$scope.GetAttendanceData = response.data;
$scope.TotalOrders = response.data.length;
});
In the following code I want to execute a series of $http requests that modify a list. When all the responses are received, I want to process the list and remove part of the content.
The problem is that when I print the list after $q.all, the Chrome console shows a length of 3, but when I expand it to read the content only 2 elements are shown. On JSFiddle I have no issues, though.
var app = angular.module('MyApp',[]);
app.controller('MyController',['$scope','$q',"$http", function($scope,$q,$http){
var loopPromises = [];
var workorders = null;
$scope.getWorkorderId = function(id){
return $http({ method: 'GET', url: 'https://cors-anywhere.herokuapp.com/https://blk.clojure.xyz/interdiv/api/v1/service/' + id })
.then(function success(response) {
return response.data;
}, function error(response) {
console.log(response);
});
}
$http({ method: 'GET', url: 'https://cors-anywhere.herokuapp.com/https://blk.clojure.xyz/interdiv/api/v1/workorder' })
.then(function success(response) {
workorders = response.data;
}, function error(response) {
console.log(response);
})
.then(function() {
if (workorders == null) {
return;
}
angular.forEach(workorders, function(value, index, obj) {
var deferred = $q.defer();
loopPromises.push(deferred.promise);
var waitResponse = $scope.getWorkorderId(value.id);
waitResponse
.then(function(res) {
obj[index].services = res;
deferred.resolve();
})
});
$q.all(loopPromises)
.then(function() {
// Should contain 3 elements, only 2 are shown
console.log(workorders);
});
});
}]);
see better in the screenshots. Console Requests
The problem was in the second part of the code not copied in the question: I was using .splice() inside angular.forEach() which changes the indices of the elements within the array.
I want to instantly showing new data after http request without reloading the whole page. I found that I can use $apply from angularjs for this. But I'm stucked. The data is not showing instantly.
This is the code in controller.
$scope.reload = function(data){
$timeout(function () {
$scope.$apply(function () {
console.log(data);
$scope.data = data;
});
});
};
// This part is not working
$scope.addMilestone = function (){
$http({
url: httpUrl + 'api/milestone/add',
method: 'post',
data: $.param($scope.formData),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function (result) {
$scope.data = result.data;
$scope.reload($scope.data);
});
};
// This part is working
$scope.deleteMilestone = function(id){
$http.get(httpUrl + 'api/milestone/delete?id=' + rowid).then(function(result){
if (result.data === 'OK'){
$http.get(httpUrl + 'api/carts/content').then(function (returns) {
$scope.data = returns.data;
$scope.reload($scope.data);
});
}
});
};
What confused me is that this method is working for deleting data, but it's not for inserting new data. In $scope.deleteMilestone, the data deleted is removed from the view instantly. I want it also work for $scope.addMilestone
Try like this for the part you have written it is not working.
$scope.addMilestone = function (){
$http.post('api/milestone/add', $scope.formData, {'Content-Type': 'application/x-www-form-urlencoded'})
.then(function (result) {
$scope.data = result.data;
$scope.reload($scope.data);
});};
Your delete is working because, you called get api after your delete, but for add you didnt make that API call, so data isnt being reloaded for you.
Change your add milestone method to,
$scope.addMilestone = function (){
$http({
url: httpUrl + 'api/milestone/add',
method: 'post',
data: $.param($scope.formData),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function (result) {
if (result){
$http.get(httpUrl + 'api/carts/content').then(function (returns) {
$scope.data = returns.data;
$scope.reload($scope.data);
});
}
});
};
i' using AngularJS v1.4.2. i have 2 html page , they have 2 controller.both controller have save event. how to use use http post method
first controller i'm calling post method given below
var promisePost = crudService.post(Countries);
promisePost.then(function (pl) {
alert("Sucessfully Inserted")
getCountry();
$stateParams.country = "";
}, function (err) {
alert("NOt Inserted")
});
second controller i'm calling post method given below
var promisePost = crudService.post(Levels);
promisePost.then(function (pl) {
alert("Sucessfully Inserted")
getLevel();
}, function (err) {
alert("NOt Inserted")
});
my app.js
myapp.service('crudService', function ($http, RESOURCES) {
//Create new record
this.post = function (Country) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveCountry",
data: Country
});
return request;
}
this.post = function (Level) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveLevel",
data: Level
});
return request;
}
});
but this code only take last post method.How to selecet post method properly. Anyone can helpme?
User countryPost and levelPost as follows and call those accordingly.
myapp.service('crudService', function ($http, RESOURCES) {
//Create new record
this.countryPost= function (Country) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveCountry",
data: Country
});
return request;
}
this.levelPost= function (Level) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveLevel",
data: Level
});
return request;
}
});
The best practice for using services is to return an object from it
myapp.factory('crudService', function ($http, RESOURCES) {
return {
saveCountry : function(){
return $http({
method: "post",
url: RESOURCES.baseUrl + "saveCountry",
data: Country
});
},
saveLevel : function(){
return $http({
method: "post",
url: RESOURCES.baseUrl + "saveLevel",
data: Level
});
}
}
});
then inject it into your controller dependencies and use it like :
crudService.saveLevel().then(function(){
//do some code here
})
Create a single post method instead and receive the url to call in it as parameter along with the data. As shown below:
this.post = function (data, remainingUrl) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + remainingUrl,
data: data
});
return request;
}
I've created a JS Object with a method that calls a $http to retrieve a value, but when the $http is done I want to assign this value to a property, I can't seem to be able to get this value:
the property this.user always ends up with the promise itself, but I want to assign the value returned from the XHR Request or undefined on failure, I think this is a context problem, I just don't know how to fix it
var Ticket = function(numint, company_id, user_id, title, description, priority, status, assignation, created_at) {
this.numint = numint;
this.company_id = company_id;
this.user_id = user_id;
this.title = title;
this.description = description;
this.priority = priority;
this.status = status;
this.assignation = assignation;
this.created_at = created_at;
this.user = undefined;
this.getUser = function() {
if(this.user_id === undefined)
return false;
var http =
$http({
method : 'GET',
url : '/users/' + this.user_id,
timeout : 100000,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
});
this.user = http
.then(
function(data) {
return data;
}
,
function() {
return undefined;
});
return http;
}
};
var http is a promise object because the return value of Angular's $http service is a promise (docs). Use .then() to get the return value once the AJAX request has returned and the promise has resolved.
var self = this;
http.then(function (data) {
self.user = data;
});
var Ticket = function(numint, company_id, user_id, title, description, priority, status, assignation, created_at) {
var self = this; // new code
self.numint = numint; //use self inseat
self.company_id = company_id;
this.getUser = function() {
if(self.user_id === undefined) // you had one preblem here, because "this" here is direrent to the this.user_id you neded, so use self
return false;
var http =
$http({
method : 'GET',
url : '/users/' + this.user_id,
timeout : 100000,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (data){
self.user = data
;},
function () {
self.user= undefined;
});
}
};
assign this to a different value OR! or us .bind.
$http({
method : 'GET',
url : '/users/' + this.user_id,
timeout : 100000,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (data){
this.user = data;
}.bind(this));