使用$resource从angular js调用rest api

calling rest api from angular js using $resource?

本文关键字:调用 rest api js angular resource 使用      更新时间:2023-09-26

我是AngularJS的新手。我想使用$resource从angular js调用rest api。但无法正确调用

这是index.html

<html ng-app="myApp">
<head>
    <script src="./angular.min.js"></script>
     <script src="./controllers.js"></script>
     <script src="./angular-resource.js"></script>
     <script src="./services.js"></script>
</head>
<body>
    <div ng-controller="loginController">
        <h1>  try to call restapi </h1>
    </div>
</body>

这是controller.js

var myapp=angular.module('myApp', ['user']);
myapp.controller('loginController', ['$scope', 'loginUser',
function ($scope, loginUser) {
 alert(loginUser.login());
}]);

这是service.js

angular.module('user', ['ngResource']).
config(function($httpProvider){
    $httpProvider.defaults.headers.common['Accept'] = "application/json";
}).factory('loginUser', function($resource){
   return $resource('http://localhost/testtext/index.php/user/login',{
   login: {method:'POST', params:{"email":"prashant@gmail.com","password":"weldone"}, isArray:false}
        });
});

实际上params-json的格式不正确,因此我在控制台上收到了这个错误

POST http://localhost/testtext/index.php/user/login?  email=prashant%40gmailcom&password=weldone 500 (PHP Error) angular.min.js:99
(anonymous function) angular.min.js:99
n angular.min.js:95
l angular.min.js:94
Resource.(anonymous function) angular-resource.js:469
(anonymous function) controllers.js:6
d angular.min.js:28
instantiate angular.min.js:28
(anonymous function) angular.min.js:52
(anonymous function) angular.min.js:43
m angular.min.js:6
i angular.min.js:43
e angular.min.js:39
e angular.min.js:39
e angular.min.js:39
(anonymous function) angular.min.js:38
(anonymous function) angular.min.js:16
e.$eval angular.min.js:88
e.$apply angular.min.js:88
(anonymous function) angular.min.js:16
d angular.min.js:27
c angular.min.js:16
rb angular.min.js:16
jc angular.min.js:15
(anonymous function) angular.min.js:163
a angular.min.js:117
(anonymous function) angular.min.js:23
m angular.min.js:6
c

正如其他人所指出的,angular看起来不错,但可能它没有以正确的php服务格式发送数据。对于一个需要表单编码数据的服务,我必须执行以下操作。希望它(或类似的东西)对你有用。

     $http({
         method: 'POST',
         url: 'rest/mm/login',
         data: 'username=' + $scope.username + "&password=" + $scope.password,
         headers: {'Content-Type': 'application/x-www-form-urlencoded'}
     }).success(function (result) {
         authService.loginConfirmed(result);
     });

(显然,为了安全起见,用户名/密码应该是url编码的)