对角js来说是新手(一周大)。我有一个要求是使用$ http发送请求。我想显示在另一个页面的响应消息中收到的错误,但我无法弄清楚如何将值传递给另一个页面。新页面与正在进行http调用的页面不同。下面是我写的代码。似乎没有什么工作。请指导我如何处理这个要求?
$http({
method : 'POST',
url : 'http://localhost:8080/abc/users',
data : JSON.stringify(toPass)
}).then(function (data) {
// this callback will be called asynchronously
// when the response is available
console.log(data.data+'a');
$scope.result="The request has been successfully submitted" +data.data.emailId;
$scope.x=data.data.emailId;
console.log('result'+x);
console.log('result');
//$location.path('/Success?{error1}');
window.location="/Success?{x}";
/*if (data.data.error){
$scope.error=data.data.error
}else{
$scope.result=data.data.emailId;
}*/
}, function (error) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log("An error encountered"+error);
var error1=error.status;
// $location.path('/Success?{error1}');
});
}
})
答案 0 :(得分:0)
通过控制器共享数据可以通过共享父控制器完成,也可以通过使用存储数据的服务(imho better)完成。服务是AngularJs中的单身人士,非常适合这种情况。
答案 1 :(得分:0)
像这样制作服务
app.service(
"friendService",
function( $http, $q ) {
// Return public API.
return({
addFriend: addFriend,
getFriends: getFriends,
removeFriend: removeFriend
});
// ---
// PUBLIC METHODS.
// ---
// I add a friend with the given name to the remote collection.
function addFriend( name ) {
var request = $http({
method: "post",
url: "api/index.cfm",
params: {
action: "add"
},
data: {
name: name
}
});
return( request.then( handleSuccess, handleError ) );
}
// I get all of the friends in the remote collection.
function getFriends() {
var request = $http({
method: "get",
url: "api/index.cfm",
params: {
action: "get"
}
});
return( request.then( handleSuccess, handleError ) );
}
// I remove the friend with the given ID from the remote collection.
function removeFriend( id ) {
var request = $http({
method: "delete",
url: "api/index.cfm",
params: {
action: "delete"
},
data: {
id: id
}
});
return( request.then( handleSuccess, handleError ) );
}
// ---
// PRIVATE METHODS.
// ---
// I transform the error response, unwrapping the application dta from
// the API response payload.
function handleError( response ) {
// The API response from the server should be returned in a
// nomralized format. However, if the request was not handled by the
// server (or what not handles properly - ex. server error), then we
// may have to normalize it on our end, as best we can.
if (
! angular.isObject( response.data ) ||
! response.data.message
) {
return( $q.reject( "An unknown error occurred." ) );
}
// Otherwise, use expected error message.
return( $q.reject( response.data.message ) );
}
// I transform the successful response, unwrapping the application data
// from the API response payload.
function handleSuccess( response ) {
return( response.data );
}
}
);