Attach parameter(s) with $http Angularjs - angularjs

I have $http request in Angularjs project.
$http.get('http://api.domain.com/index?abc=123')
.success(function (data) {
console.log('Success!');
})
.error(function (data) {
console.log('False');
});
Now, i want add token to each $http request, like
$http.get('http://api.domain.com/index?abc=123&token=456')...
I know a way to send token via header:
$http.defaults.headers.common['X-AUTH-TOKEN'] = token;
But i want use it as parameter, can i?
Regards!

You can use the params option in config of $http
var myHttpConfig = {
params: {
abc: 123,
token: 456
}
}
$http.get( url, myHttpCongig).then(function...
If you want an app wide approach to send the same params use $http interceptors
Note that success and error are now deprecated per the $http docs

Related

AngularJS : Implementing token in $http

I am very new to angularJS.
My Backend is DRF and I have successfully implemented token.
this is my token:
{
"key": "217c3b5913b583a0dc3285e3521c58b4d7d88ce2"
}
Before I implement token in backend, it was working nice:
$scope.getAllContact = function() {
var data = $http.get("http://127.0.0.1:8000/api/v1/contact")
.then(function(response) {
$scope.contacts = response.data;
});
};
But, now I am not getting how can I implement this token here
Can anyone help me in this case?
Try to use this. You need to attach the token in the headers.
$http({
url : "http://127.0.0.1:8000/api/v1/contact",
method : 'GET',
headers : {
'Content-Type' : 'application/json',
'key': "217c3b5913b583a0dc3285e3521c58b4d7d88ce2"
}
}).then(function(response){
$scope.contacts = response.data;
});
Note that, this is binding the token to only this request. Use $http interceptors to add the token to each request that you make.
See here: Angular Js - set token on header default

AngularJS access $http on onNotification event PushNotification cordova plugin

I'm using the plugin https://github.com/phonegap-build/PushPlugin/ with Angular 1.3 and I need to send the regid to server when receive "registered" event.
The problem is that I don't have $http object to call my server on this context. How can I achieve that, please?
function onNotification(e){
if(e.event == "registered"){
var req = {
method: "POST",
url: "http://myurl.com/?var="+e.regid
};
$http(req).success(function(data){
alert(data);
});
}
}
I just learned how to inject $http into the event method:
$http = angular.injector(["ng"]).get("$http");
Change $http call as follows, .success is deprecated.
$http({
method: "POST",
url: "http://myurl.com/?var="+e.regid
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
alert(response);
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Ref. : https://docs.angularjs.org/api/ng/service/$http
Regards.

Redirect angular path but hold server data

Sorry if this could be a newbie question.
So this frontend app has an interceptor.
For each request to server, the interceptor will be the first to manage the server response:
service.responseError = function (response) {
};
Now, if the server returns other status then 200, I want to redirect to another frontend path:
service.responseError = function (response) {
if (response.status === 419){
$location.path(handleError);
return;
}
return response;
};
handleError is an angular controller. Can this controller come over the server response?
Ok, doing this in interceptor:
$rootScope.interceptorData = response.data;
And then in controller injecting $rootScope and reading from it, solves it.

how to have angularJS post data to MVC controller which redirects to a view

I am posting some data to an MVC action method using AngularJS. This action method will either show its backing view or redirect to another page. Currently all that is happening is the data is getting posted but the redirect is not happening via MVC. I am getting this done using angular's window.location method. I want to know if there is a better way or if I need to post differently using Angular.
On page A I have angular scripts posting data to page B like below:
serviceDataFactory.POST('http://localhost:1234/home/B', someData, pageConfig).then(function () {
//on success
window.location = 'http://localhost:1234/home/Index';
},
function() {
//on error
window.location = 'http://localhost:1234/home/B';
});
This is my service factory
app.factory('serviceFactory', function($http, $q) {
var service = {};
//POST
service.POST = function (url, postData, conf) {
var d = $q.defer();
$http({
method: 'POST',
url: url,
data: postData,
config: conf
}).success(function(data) {
d.resolve(data);
}).error(function(error) {
d.reject(error);
});
return d.promise;
}
return service;
}
);
On Page B I want to redirect to another page. This is my page B in MVC
[HttpPost]
public ActionResult B(string someData)
{
//recieve string someData and perform some logic based on it
.
.
.
if(boolCondition)
return RedirectToAction("Index", "Home");
else
return View();
}
Here once Angular posts to the action method B, it executes all the code all the way till the if(boolCondition) statement. Since I am unable to have that redirect affected via MVC, I do that in Angular itself using the success or error block that the promise returns to.
I want to know if there is a better way to do this or if I am doing something wrong here or if this is the only acceptable way. How do I get angular to hand-off to the MVC action method and let further redirects continue from there only?
You should not use the .success() / .error() pattern with $http, because this has been deprecated. Instead, use then() with two arguments, the first argument being the success function and the second being the error function.
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.
You do not need to promisify the result of $http, because $http returns a promise. Just return $http from your service.
app.factory('serviceFactory', function($http, $q) {
var service = {};
//POST
service.POST = function (url, postData, conf) {
return $http({
method: 'POST',
url: url,
data: postData,
config: conf
});
}
return service;
});
Your Page A controller will work the same as before with this new simplified code. At the server, be sure to emit a 500 http status code in cases where you want to trigger the
function() {
//on error
window.location = 'http://localhost:1234/home/B';
}
to run. The 500 in the headers of the response will cause the AngularJS promise to run the second function in your controller.

Getting 401 error when call $http POST and passing data

I am calling a Web API 2 backend from an angularjs client. The backend is using windows authentication and I have set up the $httpProvider to use credentials with all calls and it works fine for all GETS.
Like this:
$httpProvider.defaults.withCredentials = true
But, when using the POST verb method AND passing a data js object I get a 401 error. If I remove the data object from the $http.post call it reaches the endpoint but I would like to pass up the data I need to save.
Here's an example of the client-side call:
var saveIndicator = function (indicator) {
var req = {
method: 'POST',
url: baseUrl + "/api/indicators",
data: indicator
};
return $http(req).then(function (response) {
return response.data;
});
};

Resources