This current code when ran returns TypeError: Services.updateUserData.set is not a function
Controller
Services.updateUserData.set($rootScope.user);
Services.js
this.updateUserData = function() {
return {
set: function(data) {
console.log(data);
$http({
method: 'POST',
url: 'api/data/',
data: {'data': data},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
}).success(function(data, status, headers, config) {
console.log(data);
}).error(function(data, status, headers, config) {
console.log(data);
});
}
}
}
The code below works but I would much rather have a get and set function within updateUserData so that I am not duplicating work.
Current Code
Controller
Services.updateUserData($rootScope.user);
Services.js
this.updateUserData = function() {
console.log(data);
$http({
method: 'POST',
url: 'api/data/',
data: {'data': data},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
}).success(function(data, status, headers, config) {
console.log(data);
}).error(function(data, status, headers, config) {
console.log(data);
});
}
updateUserData is a function and hence there is no property called set. The option is either convert it to object
this.updateUserData={set:function(){}}
or invoke it
Services.updateUserData().set($rootScope.user);
before accessing set
Related
In my App I need to do a request to save some data (this request is little slow) but the user can do another request in same time, when he did this, angular was waiting for the first request (not assync). How Can I do two requests whithout waiting for other?
My slow service:
app.service('PedSaveService',["$http", "$q","BASEURL",
function ($http, $q,BASEURL) {
var self = this;
self.Save = function (pedidoData) {
var deferred = $q.defer();
$http({method: 'POST',async: true, url: BASEURL.REST_SAVE, headers: {'Content-Type': 'application/json;charset=utf-8'}, data : pedidoData})
.success(function (response, status, headers, config) {
deferred.resolve(response, status, headers, config);
})
.error(function (response, status, headers, config) {
deferred.reject(response, status, headers, config);
});
return deferred.promise;
}
self.Save = function(pedidoData) {
$http({
method: 'POST',
async: true,
url: BASEURL.REST_SAVE,
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
data: pedidoData
}).then(function(res) {
return res;
}); }
Your code in service should be this.
I want to filter retrived sharepoint list using filterFilter.But it is giving ***error as:**angular.min.js:89 TypeError: filterFilter is not a function*****
Not able to inject filter to controller since am using $https.
Below is the code,
$scope.update=function()
{
$scope.drop=$scope.states.Id;
console.log($scope.drop);
$http({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/Lists/getByTitle('List')/items?$select=State/Title,Title,Id&$expand=State/Title",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" }
})
.success(function (data, status, headers, config) {
$scope.city= filterFilter(data.d.results,{State:$scope.drop});
console.log($scope.city);
})
.error (function(data, status, headers, config) { })
}
Thank you for your reply ,i got my answer,Complete code is below
app.controller('Ctrl', function($filter,$scope,$http,filterFilter)
{
$http({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/Lists/getByTitle('States')/items",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" }
})
.success(function (data, status, headers, config) {
$scope.State=data.d.results;
console.log($scope.State);
})
.error (function(data, status, headers, config) { })
$scope.update=function()
{
$scope.drop=$scope.states.Id;
console.log($scope.drop);
$http({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/Lists/getByTitle('City')/items?$select=State/Title,Title,Id,*&$expand=State",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" }
})
.success(function (data, status, headers, config) {
$scope.city=filterFilter(data.d.results,{StateId:$scope.drop});
console.log($scope.city);
})
.error (function(data, status, headers, config) { })
}
});
If you use * in $select,Lookup field Id can be retrieved,using that you can compare :)
here is my angularjs request whenever I submit a request it returns error and no delay.
var req = $http({
method: 'POST',
url: 'https://localhost:44300/authentication/login',
data: { UserID: Username, Password: Password },
dataType: "json"
});
req.success(
function (result) {
alert('success');
});
req.error(function (result) {
alert('something went wrong');
});
Thanks in advance.
thats how I do and it always works fine
var deferred = $q.defer();
var url = 'your url';
$http({
method: 'POST',
url: url,
data: {}
})
.then(function(data, status, headers, config) {
deferred.resolve(data);
})
.catch(function(data, status, headers, config) {
deferred.reject(msg);
});
return deferred.promise;
I am trying to access the http headers in my angular controller but I am getting undefined. Also, I am able to see the header response in my angular service which is not reflecting in my controller. Can someone please tell me what I am missing? Please see the code below:
Service:
cmApp.service('supplierService', function ($http, $q) {
this.getSuppliers = function (orderByColumn, skipRows, takeRows) {
var deferred = $q.defer();
$http({
method: 'GET',
url: 'api/supplier',
params: { orderBy: orderByColumn, skip: skipRows, take: takeRows },
timeout: 30000,
cache: false
}).
success(function (data, status, headers, config) {
// any required additional processing here
deferred.resolve(data, status, headers, config);
}).
error(function (data, status) {
deferred.reject(data, status, headers, config);
});
return deferred.promise;
}
Controller:
supplierService.getSuppliers($scope.orderby, $scope.skip, $scope.take)
.then(function (data, status, headers, config) {
**//getting undefined here.**
$scope.totalRecords = parseInt(headers('X-TotalRowCount'));
$scope.suppliers = data;
}, function (error) {
// error handling here
});
I have found the solution by myself. All I have to do is create an array and add all those values to the same & return it to the controller. Please see the updated code below:
Service:
cmApp.service('supplierService', function ($http, $q) {
this.getSuppliers = function (orderByColumn, skipRows, takeRows) {
var deferred = $q.defer();
$http({
method: 'GET',
url: 'api/supplier',
params: { orderBy: orderByColumn, skip: skipRows, take: takeRows },
timeout: 30000,
cache: false
}).
success(function (data, status, headers, config) {
// any required additional processing here
var results = [];
results.data = data;
results.headers = headers();
results.status = status;
results.config = config;
deferred.resolve(results);
}).
error(function (data, status) {
deferred.reject(data, status, headers, config);
});
return deferred.promise;
}
Controller:
supplierService.getSuppliers($scope.orderby, $scope.skip, $scope.take)
.then(function (response) {
$scope.suppliers = response.data;
$scope.totalRecords = parseInt(response.headers["x-totalrowcount"]);
}, function (error) {
// error handling here
});
This question is old, but $http() returns a promise itself. you can just return that from your service, no need to create a new promise. You can do this even after using .success() and .error(), or for that matter even after using a .then(), they keep chaining.
I had to access Token and TokenExpiry time from response headers of my Rest Service,then store it in my $rootScope.
Here is the code I used:
$scope.Authenticate=function(){
var EncDecUserPass=decodeURIComponent(encodeURIComponent($scope.LoggedUserName+':'+$scope.LoggedUserPassword)) ;
$http(
{method: 'GET',
url: 'http://localhost:53256/api/Products/Authenticate',
cache: false,
headers:{'Authorization':'Basic '+window.btoa(EncDecUserPass)}
}
).success(function(data, status, headers, config) {
//Here it goes
$rootScope.token=headers().token;
$rootScope.tokenExpirySec=headers().tokenexpiry;
}).error(function(data, status, headers, config) {
alert('Invalid User');
});
}
I've just started learning Angular.js. How do I re-write the following code in Angular.js?
var postData = "<RequestInfo> "
+ "<Event>GetPersons</Event> "
+ "</RequestInfo>";
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState == 4 || req.readyState == "complete") {
if (req.status == 200) {
console.log(req.responseText);
}
}
};
try {
req.open('POST', 'http://samedomain.com/GetPersons', false);
req.send(postData);
}
catch (e) {
console.log(e);
}
Here's what I have so far -
function TestController($scope) {
$scope.persons = $http({
url: 'http://samedomain.com/GetPersons',
method: "POST",
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
$scope.data = data; // how do pass this to $scope.persons?
}).error(function (data, status, headers, config) {
$scope.status = status;
});
}
html
<div ng-controller="TestController">
<li ng-repeat="person in persons">{{person.name}}</li>
</div>
Am I in the right direction?
In your current function if you are assigning $scope.persons to $http which is a promise object as $http returns a promise object.
So instead of assigning scope.persons to $http you should assign $scope.persons inside the success of $http as mentioned below:
function TestController($scope, $http) {
$http({
url: 'http://samedomain.com/GetPersons',
method: "POST",
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
$scope.persons = data; // assign $scope.persons here as promise is resolved here
}).error(function (data, status, headers, config) {
$scope.status = status;
});
}
Here is a variation of the solution given by Ajay beni. Using the method then allows to chain multiple promises, since the then returns a new promise.
function TestController($scope) {
$http({
url: 'http://samedomain.com/GetPersons',
method: "POST",
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(response) {
// success
},
function(response) { // optional
// failed
}
);
}
use $http:
AngularJS: API: $http
$http.post(url, data, [config]);
Implementation example:
$http.post('http://service.provider.com/api/endpoint', {
Description: 'Test Object',
TestType: 'PostTest'
}, {
headers {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose'
}
}
).then(function (result) {
console.log('Success');
console.log(result);
}, function(error) {
console.log('Error:');
console.log(error);
});
Lets break this down: Url is a little obvious, so we skip that...
data: This is the body content of your postman request
{
Description: 'Test Object',
TestType: 'PostTest'
}
config: This is where we can inject headers, event handlers, caching... see AngularJS: API: $http: scroll down to config Headers are the most common postman variant of http that people struggle to replicate in angularJS
{
headers {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose'
}
}
Response: the $http actions return an angular promise, I recommend using .then(successFunction, errorFunction) to process that promise see AngularJS: The Deferred API (Promises)
.then(function (result) {
console.log('Success');
console.log(result);
}, function(error) {
console.log('Error:');
console.log(error);
});