【问题标题】:Angular resource REST has no method '$save'Angular 资源 REST 没有方法“$save”
【发布时间】:2013-08-23 08:11:50
【问题描述】:

我想使用 $resource 与 REST API 进行交互,但在调用 save 方法时出现 has no method '$save' 错误。我的代码灵感来自AngularJS $resource RESTful example

上的答案
myapp.factory('Monitoring', function($resource) {
   return $resource('http://localhost:8080/wepapp/network/v1/cronjobs/:id', { id: '@id' } );
});

Q1:@{ id: '@id' } 中的作用是什么?我在大多数示例中都找到了它。

myapp.factory('MonitoringCRUDControllerService', ['Monitoring', function(Monitoring) {
    return {
        create: function(id, command, schedule) {
            console.log("create");
            console.log(command);
            console.log(schedule);
            Monitoring.id = id;
            Monitoring.command = command;
            Monitoring.schedule = schedule;
            console.log(Monitoring);
            Monitoring.$save();
        }
    }
}]);

Monitoring 对象被正确注入:

function Resource(value){
        copy(value || {}, this);
      } 

调用$save 失败,错误为has no method '$save'

Q2:保存前$的目的是什么?

Q3:让 save 方法起作用我缺少什么?

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    您需要像这样创建Monitoring 类的实例(未测试):

    var m = new Monitoring({id:id});
    m.command = command;
    m.schedule = schedule;
    m.$save();
    

    文档(http://docs.angularjs.org/api/ngResource.$resource)有一个类似的例子:

    var newCard = new CreditCard({number:'0123'});
    newCard.name = "Mike Smith";
    newCard.$save();
    

    我不久前就@ 签名问过同样的问题:"at" sign in parameter names in resource definition。基本上@ 符号意味着该值将从对象的属性中读取。或如同一文档所述:

    如果参数值以 @ 为前缀,则该值 参数是从数据对象中提取的(对非 GET 有用 操作)。

    $ 不是任何特殊字符,它只是方法名称的一部分。

    【讨论】:

    • 错误消失了,但我注意到在 Chrome 中,被调用的 URL 不包含端口号,方法类型为 OPTIONS:OPTIONS http://localhost/wepapp/network/v1/cronjobs。这种行为有什么原因吗? $resource 是否处理 JSONP?
    • 我认为 JSONP 行不通。我认为 Angular 需要来自 URL 的 JSON 数据。我不确定为什么它省略了端口号。文档说端口号受到尊重。尝试在默认端口上运行它,看看它是否有效。
    • 对于我需要使用 '\\:' 转义 : 的端口
    • 你用的是最新的angular吗?
    • 它在你转义冒号之前执行OPTIONS的原因是因为没有端口号,这是一个不同的域,所以浏览器发送了一个所谓的CORS“预检”请求。
    猜你喜欢
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多