【问题标题】:Adding a function to $resource prototype向 $resource 原型添加函数
【发布时间】:2014-05-28 05:26:48
【问题描述】:

我正在尝试将视图函数添加到 Angular $resource。我通过原型将它添加到 $resource 但由于某种原因原型函数中的“this”引用不正确,因此所有属性都未定义。奇怪的是,虽然在 console.log 中,这似乎具有正确返回所需的所有属性。

http://plnkr.co/edit/YsTlAztjEKjn3piQAem2?p=preview

app.factory("Now", function($resource) {

  var Now = $resource("http://date.jsontest.com/");

  Now.prototype.$dateTime = function() {
    console.log("2", this); // this has date and time properties, good
    return this.date + " " + this.time;
  };

  return Now;
});

app.controller("TestController", function(Now) {
  var now = new Now();
  now.$get();
  console.log("1", now); // prototype has the $dateTime function!
  console.log("3", now.$dateTime()); // but it returns undefined, bad
});

【问题讨论】:

    标签: javascript angularjs prototype


    【解决方案1】:

    实际上,您的错误是您在资源返回数据之前调用了 $dateTime。

    看到这个plunk

    我上面的答案似乎有效的唯一原因是它正在被插值,当资源最终返回时,再次调用 datetime 函数。但是如果你让代码保持不变,它仍然会失败

    【讨论】:

      【解决方案2】:

      您正在尝试使用 this 的属性,而模型仍在从服务器获取,这导致当您请求这些属性时未定义这些属性。您需要使用从 $get 返回的对象上可用的 promise 方法,以保证请求已完成。

      这个

      now.$get();

      应该变成这个

      now.$get().then(function() { console.log("1", now); console.log("3", now.$dateTime()); });

      【讨论】:

      • 干得好,答案正确。不过必须把它交给 Erik Donohoo,因为他先得到它。
      【解决方案3】:

      您的错误在于使用.factory。它期望返回一个对象,但 $resource 是一个函数。把它改成.service就可以了

      app.service("now", function($resource) {
      

      完整代码:http://plnkr.co/edit/n31MMNTlKV3i04HdXUms?p=catalogue

      var app = angular.module("test", ["ngResource"]);
      
      app.service("now", function($resource) {
      
        var now = $resource("http://date.jsontest.com/");
      
        now.prototype.dateTime = function() {
          return this.date + " " + this.time;
        };
      
        return now;
      });
      
      app.controller("TestController", function($scope, now) {
        $scope.now = now.get();
      });
      

      【讨论】:

      • 工厂返回什么都没有关系。事实上,像你一样使用.service 具有相同的效果并且没有意义,因为.service 是用于构造函数的。
      猜你喜欢
      • 2014-05-26
      • 2015-10-16
      • 2020-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多