Is there such a thing as a finally with AngularJS $http? - angularjs

I have code like this:
$http({
method: 'POST',
url: "/api/Account/Register",
data: {
userName: userName,
password: password,
confirmPassword: confirmPassword
}
})
.success(function () {
successCallback();
})
.error(function (data) {
errorCallback(data);
})
Is there any way that I could add in a finallyCallback to this with AngularJS ?

Yes, there is a finally method since 1.2.0rc1, as shown by the documentation. The method was known as always since 1.1.5.
$http({
method: 'POST',
url: "/api/Account/Register",
data: {
userName: userName,
password: password,
confirmPassword: confirmPassword
}
})
.success(successCallback)
.error(errorCallback)
.finally(finallyCallback)
;

The promise returned by $http is the same as any other promise created with the $q service. That means it will have a finally method:
$http({ /* ... */ })
.success(function () {})
.error(function () {})
.finally(function () {});
From the $http docs:
Returns a promise object with the standard then method and two http specific methods

Related

Angularjs bad request URL

I have a problem with the wrong URL in Request URL. I have api in Laravel, the address to him is: api.shop.local - this is vhost. When I send a request from angular using POST, in the Network tab in the console, in RequestURL there appears: client.shop.local instead of api.shop.local.
What I doing wrong?
This is my code:
JS
$scope.login = function (data) {
console.log(data);
$http({
method: 'POST',
url: 'authenticate',
data: {email: data.username, password: data.password}
}).then(
function (res) {
console.log('succes !', res.data);
},
function (err) {
console.log('error...', err);
}
);
};
And routes in api Laravel:
Route::group(['prefix' => 'api'], function()
{
Route::resource('authenticate', 'AuthenticateController', ['only' => ['index']]);
Route::post('authenticate', 'AuthenticateController#authenticate');
});

POSTing value from Angular to MVC controller results in null value

I am attempting to pass a value from angular to my MVC Core controller to use in a repository function as simple string. However, I've noticed that it's passing a null value to the MVC controller. I don't want to create an MVC model just to use the POSTed JSON as a string.
Function excerpt from MVC controller
[HttpPost("api/specials/GetCurrentSpecialsBySiteID")]
public ActionResult GetCurrentSpecials([FromBody] string siteID)
{
return Ok(_repo.GetAllSpecialsBySiteID(siteID));
}
$Http Angular function
$http({
method: 'POST',
url: '/api/specials/GetCurrentSpecialsBySiteID',
data: siteID,
headers: { 'Content-Type': 'application/json;charset=UTF-8' }
})
.then(function (response) {
// success
console.log(response);
vm.Specials.push(response.data);
angular.copy(response.data, vm.Specials);
console.log(vm.Specials);
// clear the form
vm.newSpecials = {};
}, function (response) {
// failure
console.log("Error !" + response.data);
vm.errorMessage = "Failed to save subscription";
})
.finally(function () {
vm.isBusy = false;
});
In mvc controller you are passing action parameter as string.
Please check you "siteID" Type in your JS.
method: 'POST',
url: '/api/specials/GetCurrentSpecialsBySiteID',
data: siteID,
headers: { 'Content-Type': 'application/json;charset=UTF-8' }
})
From your example it looks like you should probably be performing a GET rather than a POST, however you can adapt your methods as follows to get up and running:
[HttpPost("api/specials/GetCurrentSpecialsBySiteID")]
public ActionResult GetCurrentSpecials([FromUri] string siteID)
{
return Ok(_repo.GetAllSpecialsBySiteID(siteID));
}
And your angular function:
$http.post('/api/organisations/test?siteID=' + siteID)
.then(function (response) {
...
})
.finally(function () {
...
});
Try to pass object in $Http Angular function.
$http({
method: 'POST',
url: '/api/specials/GetCurrentSpecialsBySiteID',
data: {siteID: siteID},
headers: { 'Content-Type': 'application/json;charset=UTF-8' }
})
.then....
For more just check $http service documentation here.

null with receipt data in angular $http

This is my code:
$scope.doLogin = function() {
$http({
method: "POST",
url: "http://localhost:8000/api/v1/user/user_signin",
data: { username: $scope.user.username, password: $scope.user.password },
headers: { 'Content-Type': 'application/json' },
responseType:'json'
}).success(function (data) {
console.log('data success');
console.log(JSON.stringify(data));
})
.error(function(data, status, headers,config){
console.log('data error');
});
};
Consol says:
data success
null
What I do wrong?
P.S.: API request is correct - I checked it in postman.
You set responseType to 'json' make sure that your server side is also sending the response compatible to your format 'json'.
Or simply remove the response type check if it works

Cannot get the data in the controller from the service

app.service('customersService', function ($http) {
this.getCustomer = function (id) {
$http({
method: 'GET',
url: '/getCustomer',
params: {id: id},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
}).success(function(data) {
console.log(data);
return data;
})
};
});
Cannot get the data in the controller from the service
The problem with this code is when i try to run this
customersService.getCustomer(customerID).then
It generates an error mentioned below:
angular.js:13294 TypeError: Cannot read property 'then' of undefined.
The main thing is the call to the service is generated and if i try to print the results on the console in the service the data is there. However i cannot get the data in my controller.
You get that error becuase you are not returning the promise from $http GET request.
Edit your code like this:
app.service('customersService', function ($http) {
this.getCustomer = function (id) {
return $http({
method: 'GET',
url: '/getCustomer',
params: {id: id},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
});
};
});
And then with .then() in your controller, you handle the response data.
app.controller('myController', function($scope, customerService){
customersService.getCustomer(customerID)
.then(function(response){
$scope.data = response;
})
})
You simply forget to return the $http promise that is why undefined is returned. You need to do the following:
...
return $http({ ...
Try given code.
app.service('customersService', function ($http) {
var getCustomer = function (id) {
return $http({
method: 'GET',
url: '/getCustomer',
params: {id: id},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
})
};
var customersService = {
getCustomer: getCustomer
}
return ProfileService;
});

Angular $http get method does not send correct data to server

I am new at angular. I use angular.js and webapi. I have a request like below.
[HttpGet]
public RecordDTO[] GetMyFiles(UserClass usr,int uId,int fId)
{
}
my webapi call is like this. UserClass parameter is a class that has two string field(name,password). My angular code is like below.
$scope.GetMyFiles= function () {
var user = { Name:'xx',Password:'xx' };
var data = {usr:user, uId: 11, fId: 56};
$http({
url:"../api/Home/GetMyFiles",
method: 'GET',
//headers: { 'Content-Type': 'application/json' },
params: data
})
.success(function (data) {
alert("OK");
})
.error(function (data) {
alert("error");
});
};
My problem is UserClass is null. It takes uId and fId parameters, but first parameter comes null.
How can I correct this?
Thanks in advance.
As the default content-type for $http is JSON, check what your service is attending. If its JSON, you should stringify your data to pass them to your webapi :
params: JSON.stringify(data)
if you need to SEND data to the server, you should make a $http.post call. I think the problem because you are not specifiying the content-type of the header.
please try this:
$http.post('/api/Home/GetMyFiles', data , {
headers: { 'Content-Type': 'application/x-www-form-urlencoded;' }
}
).success(function(data) })
.error(function(err){});
Tell me if it works, and if you need any help let me know. Happy Coding. ;)
Change $http method from GET to POST. Also change params: data to data: data. I tried this code in my local PC and it works correctly.
Controller:
[HttpPost]
public RecordDTO[] GetMyFiles(UserClass usr, int uId, int fId )
{
}
JavaScript:
$http({
url: url,
method: 'POST',
data: data
})
.success(function (data) {
alert("OK");
})
.error(function (data) {
alert("error");
});

Resources