草庐IT

javascript - $resource service .success 不是函数

coder 2023-11-02 原文

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

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

成功不像 $http 方式那样存在?

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

  • HTTP GET“类” Action :Resource.action([参数], [成功], [错误])

  • 非 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);
            });
        }
    };
});

最佳答案

您的 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
            });
        }
    }
});

以上示例假设您要在请求正文中传递用户凭据。假设您使用的是 SSL,这没问题,但首选方法是使用 Authorization header 。例如,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 .

关于javascript - $resource service .success 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34256322/

有关javascript - $resource service .success 不是函数的更多相关文章

  1. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  2. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  3. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  4. ruby - 在 Ruby 中按名称传递函数 - 2

    如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只

  5. 【Java 面试合集】HashMap中为什么引入红黑树,而不是AVL树呢 - 2

    HashMap中为什么引入红黑树,而不是AVL树呢1.概述开始学习这个知识点之前我们需要知道,在JDK1.8以及之前,针对HashMap有什么不同。JDK1.7的时候,HashMap的底层实现是数组+链表JDK1.8的时候,HashMap的底层实现是数组+链表+红黑树我们要思考一个问题,为什么要从链表转为红黑树呢。首先先让我们了解下链表有什么不好???2.链表上述的截图其实就是链表的结构,我们来看下链表的增删改查的时间复杂度增:因为链表不是线性结构,所以每次添加的时候,只需要移动一个节点,所以可以理解为复杂度是N(1)删:算法时间复杂度跟增保持一致查:既然是非线性结构,所以查询某一个节点的时候

  6. C51单片机——实现用独立按键控制LED亮灭(调用函数篇) - 2

    说在前面这部分我本来是合为一篇来写的,因为目的是一样的,都是通过独立按键来控制LED闪灭本质上是起到开关的作用,即调用函数和中断函数。但是写一篇太累了,我还是决定分为两篇写,这篇是调用函数篇。在本篇中你主要看到这些东西!!!1.调用函数的方法(主要讲语法和格式)2.独立按键如何控制LED亮灭3.程序中的一些细节(软件消抖等)1.调用函数的方法思路还是比较清晰地,就是通过按下按键来控制LED闪灭,即每按下一次,LED取反一次。重要的是,把按键与LED联系在一起。我打算用K1来作为开关,看了一下开发板原理图,K1连接的是单片机的P31口,当按下K1时,P31是与GND相连的,也就是说,当我按下去时

  7. ruby-on-rails - 将字符串转换为 ruby​​-on-rails 中的函数 - 2

    我需要一个通过输入字符串进行计算的方法,像这样function="(a/b)*100"a=25b=50function.something>>50有什么方法吗? 最佳答案 您可以使用instance_eval:function="(a/b)*100"a=25.0b=50instance_evalfunction#=>50.0请注意,使用eval本质上是不安全的,尤其是当您使用外部输入时,因为它可能包含注入(inject)的恶意代码。另请注意,a设置为25.0而不是25,因为如果它是整数a/b将导致0(整数)。

  8. ruby-on-rails - 使用 javascript 更改数据方法不会更改 ajax 调用用户的什么方法? - 2

    我遇到了一个非常奇怪的问题,我很难解决。在我看来,我有一个与data-remote="true"和data-method="delete"的链接。当我单击该链接时,我可以看到对我的Rails服务器的DELETE请求。返回的JS代码会更改此链接的属性,其中包括href和data-method。再次单击此链接后,我的服务器收到了对新href的请求,但使用的是旧的data-method,即使我已将其从DELETE到POST(它仍然发送一个DELETE请求)。但是,如果我刷新页面,HTML与"new"HTML相同(随返回的JS发生变化),但它实际上发送了正确的请求类型。这就是这个问题令我困惑的

  9. ruby-on-rails - 只有当不是 nil 时才执行映射? - 2

    如果names为nil,则以下中断。我怎样才能让这个map只有在它不是nil时才执行?self.topics=names.split(",").mapdo|n|Topic.where(name:n.strip).first_or_create!end 最佳答案 其他几个选项:选项1(在其上执行map时检查split的结果):names_list=names.try(:split,",")self.topics=names_list.mapdo|n|Topic.where(name:n.strip).first_or_create!e

  10. ruby - 在 ruby​​ 中使用 .try 函数和 .map 函数 - 2

    我需要从json记录中获取一些值并像下面这样提取curr_json_doc['title']['genre'].map{|s|s['name']}.join(',')但对于某些记录,curr_json_doc['title']['genre']可以为空。所以我想对map和join()使用try函数。我试过如下curr_json_doc['title']['genre'].try(:map,{|s|s['name']}).try(:join,(','))但是没用。 最佳答案 你没有正确传递block。block被传递给参数括号外的方法

随机推荐