how to redirect with angularjs - angularjs

I have server side code which sends a response back (expressjs) to state if the user is authenticated or not.
I use $http post request and get the success back if all is ok. If user is authenticated I need to redirect the user to the relevant page.
My code here currently does not work or throw an error either when using debugging tools
$http({ method: 'POST',
url: '/login',
data: JSON.stringify({'username' : $scope.user.username, 'password' : $scope.user.password }),
headers: {'Content-Type': 'application/json'}}).
success(function (data, status, headers, config) {
$scope.invalid = false;
$window.location.href = '#/admin/';
}).
error(function (data, status, headers, config) {
console.log(status);
$scope.list = data;
});
return;
};
Any help would be great.

You can use $location to redirect
$location.path( "#/admin/" );
I would have expected your $window.location to also perform the redirect, so there could be something else going on. Do you have a route for '#/admin/' set up in a routeProvider? If not the default route would execute, if specified.

Related

store response header value during angular http post

I am making an angular http post to an API which like this
$http({
method: 'POST',
url: 'http://api/ClientEndpoint',
data: register,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
}).error(function (data, status, headers, config) {
alert(data);
});
which is returning the following response
But I am not able to store the response path in a variable. How can I do that?
It is cross domain scenario and this is the response being showed in chrome console
I want to access store the ClientEndpoint value
Did you forget the .success(function (data) { }) callback ? just like the .error() you put after the http() function
i hope this will solve your problem ;)
Use the headers variable in either your .succes(response, headers) or .error(response, headers).
E.g :
.success(function(data, status, headers, config) {
//Success Handling
});
.error(function(data, status, headers, config) {
//Error Handeling
});
This only works if you are on the same domain as the server, if it's cross domain, the server has to send the Access-Control-Expose-Headers for you to make this work.

AngularJS $http.post how to set the json data into request body

I am trying to send the post request with json data to server. But seems angularJS $http.post method does not set the data into body. How can I make it set the data into body?
The remote server is implemented use asp.net webapi and will read the data from body. so I need to set the json data into request body.
How can I implement this please? Thanks.
If the request send to same site, then it works. But if I send the request to CROS server, it does not work.
In the remote backend server, I already updated the webconfig to make it support CROS call, but it still does not work.
$http.post(resourceUri, requestData)
.success(function (response) {
})
.error(function (data, status, header, config) {
});
You could build the request like this:
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': "application/json"
},
data: { test: 'test' }
}
$http(req).success(function(){...}).error(function(){...});
YOu can do it as follows
1. make a controller
2. make a add data to the call
syntax for the post call is as follows
$http.post(url, data, [config])
app.controller('controller', function ($scope, $http, $routeParams) {
$http.post('url',data.call1($routeParams.id))
.success(function (response) {
$scope.response = response;
})
.error(function (data, status, headers, config) {
});
});
var data = {
call1:
function (value) {
return {'key': value, 'key': 'some text'};
}
}

Get data and after that routing

I want to make $http request, get results and according to data i get to route to view1 or view2. How can i do it in angular? Does somebody have example?
It should be some
$http({
url: 'API/v1/User/GetUserInfo',
method: "GET",
headers: { 'Content-Type': 'application/json' }
}).success(function (data, status, headers, config) {
//Something like this
var myVar=data.myVariable;
if(myVar==1){
$routeProvider.otherwise({ redirectTo: '/view1' });
}else{
$routeProvider.otherwise({ redirectTo: '/view2' });
}
}).error(function (data, status, headers, config) {
$scope.error = "There are problems with connection to server. Status:" + status + " Please, try to connect later.";
$scope.validationClass = "invalid";
});
and after that
Use to $location service to go to a specific path/route. Angular routing listens to changes on the location and will trigger all necessary actions.
if (myVar == 1) {
$location.url('/view1');
} else {
$location.url('/view2');
}

$http - null plain text response

I have an $http POST call in AngularJS that won't show the server response if the request was bad.
myFactory.create = function(formData) {
deferred = $q.defer()
$http({method: 'POST', url: url, responseType: 'json', data: formData})
.then(function(data) {
deferred.resolve(data);
}, function(response, status, headers, config) {
deferred.reject(response);
});
return deferred.promise;
};
When I submit incorrect data, the API responds with a 400 - Bad Request. If I look at the response in Chrome Developer tools, there is a plain text message: "Vertical is not correct." However, that message is not in the response on the $http error callback.
I can get everything else (status, headers and config) but my response data is null.
Successful POSTs are processed correctly so I know that the function generally works.
Any idea why I would be able to see the response in Chrome but not able to access it via $http?
You can refactor to this:
myFactory.create = function(formData) {
var url = 'api/create';
return $http({
method: 'POST',
url: url,
responseType: 'json', //Are you sure that it is returning a json??
data: formData
});
};
Then check the return of the promise like this wherever you wish to call it,
myFactory.create().then(
function(data){
console.dir(data);
},function(response, status, headers, config) {
console.dir(response);
});
This should work and you should see the data on the logs.

How to configure Angular.js to user default host?

For example, I have this call:
$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
I need it to request http://my-api-url.com/someUrl, but I don't want to type it everywhere because it will change in the future.
How can I configure it globally ?
Use a constant:
var myApp = angular.module('myApp',[]);
myApp.constant('myUrls', {
someUrl: 'http://my-api-url.com/someUrl,',
});
mayApp.directive('myDirective', ['myUrls', function (myUrls) {
return {
....
// use myUrls.someUrl
....
};
}]);
AngularJS Module
i don't think you can, that would cripple any other call to other url so what you could do is setting a host variable in a service pointing to the host you want and then in every call set your url as.
$http.get(service.host+'/somePath'}).
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
});

Resources