【问题标题】:$resource service .success is not a function$resource service .success 不是函数
【发布时间】:2015-12-15 10:25:27
【问题描述】:

我想用 AngularJS、Node 和 MongoDB 实现登录方法。我已经构建了一个用于发送请求的 Restful API。

当我尝试执行 GET 请求时,控制台会出现此错误TypeError: UserService.logIn(...).success is not a function

成功不存在像$http 方式?

我也找到了这个,但我不明白如何调整它以适合我的代码。

  • HTTP GET“类”操作:Resource.action([parameters], [success], [错误])

  • 非 GET “类”操作:Resource.action([parameters], postData, [成功],[错误])

  • 非 GET 实例操作:instance.$action([parameters], [success], [错误])

Service.js

var appServices = angular.module('starter.services', ['ngResource']);

appServices.factory('UserService', function ($resource) {
    return {
        logIn: function (email, password) {
            return $resource("http://localhost:3000/users/login", {
                email: email,
                password: password
            });
        }
    }
});

Controller.js

    var apps = angular.module('starter.controller', []);
apps.controller('loginCtrl', function ($scope, $ionicPopup, $state, UserService) {

    $scope.doLogin = function doLogin(email, password) {


        if (email != null && password != null) {

            UserService.logIn(email, password).success(function (data) {
                $state.go('tabs.home');

            }).error(function (status, data) {

                var ionicPop = $ionicPopup.alert({
                    title: 'Login Failed',
                    template: 'Invalid email or password.\nPlease try again!'
                });
                console.log(status);
                console.log(data);
            });
        }
    };
});

【问题讨论】:

  • 在这里使用$resource 有什么意义?为什么不$http
  • 我认为 .success() 和 .error() 方法已被弃用。请改用 .then(successHandler, errorHandler) 或 .then(successHandler).catch(errorHandler)。
  • @ShaunScovil 我试过这个,但错误与前一个相同,但用 then 而不是成功。我认为问题在于我传递的参数(电子邮件,密码)
  • 在下面查看我的答案。通常,您将创建一个处理登录/注销的身份验证服务,并在用户登录时设置一个带有令牌的标头,该令牌可以传递给每个其他 API 端点调用。所以你的UserService 可能是一个配置为点击http://localhost:3000/users/:userId 的资源,你可以在登录后调用它,传递当前登录的用户ID,如UserService.get(userId);

标签: javascript angularjs mongodb angular-resource


【解决方案1】:

您的 UserService.logIn() 方法未按预期运行的原因是,您正在返回一个 Resource 的新实例,但实际上从未在其上调用方法。

// This returns an instance of Resource, which is configured incorrectly.
// The second argument suggests that the URL has :email and :password
// parameters, which it does not. As a result, the email and password
// would be appended to the URL as query params (very insecure!).
return $resource("http://localhost:3000/users/login", {
    email: email,
    password: password
}); 

使用 $resource,您可以定义其他方法或修改现有的 getsavequerydelete 方法。但是,这仅对支持 CRUD operations 的 API 端点有用。

对于登录调用,您不需要创建资源,因为您不会执行 CRUD 操作。请改用$http

var appServices = angular.module('starter.services', ['ngResource']);

appServices.factory('authService', function ($http) {
    return {
        logIn: function (email, password) {
            return $http({
                url: 'http://localhost:3000/users/login',
                method: 'POST',
                data: {
                    email: email,
                    password: password
                },
                headers: {
                    'Content-Type': 'application/json'
                },
                withCredentials: true
            });
        }
    }
});

以上示例假设您要在请求正文中传递用户凭据。 ok 假设您使用的是 SSL,但首选方法是使用 Authorization 标头。例如,Basic Auth 会更安全一些。

更新

事实证明,$resource 的方法不会返回 Promise。它们返回资源实例,带有$promise 属性。因此,例如,您可以执行以下操作:

// Using the .save() method, which performs a POST
$resource('http://localhost:3000/users/login').save({email: 'foo@bar.com', password: 'baz'})
    .$promise.then(handleSuccess, handleError);

不过,我还是建议使用$http 作为登录端点。但是,如果您需要使用$resource,请查看this plunker

【讨论】:

    猜你喜欢
    • 2017-05-01
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    • 2016-12-17
    相关资源
    最近更新 更多