当评估值并通过控制器发送时,Angular $ scope.value不会更新

时间:2017-04-13 13:19:10

标签: javascript angularjs angular-promise

这是Fiddle我用来学习角度js

简而言之,正在使用JS文件:

angular.module('ngApp', [])

.service('myownservice', '$q', function ($timeout, $q) {

    this.httpcall = function() {
         var httpresp = "1818";
         //making an http call over here. 
         return httpresp;
    };

    this.UpdateSomeData = function () {
        var defer = $q.defer();
        myownservice.httpcall().then(function(data) {
                defer.resolve(data);
        });
        return defer.promise;
    };
 })
 .controller('ctrl', function ($scope, myownservice) {
    $scope.value = UpdateSomeData();
 });

html page

<div ng-controller="ctrl">{{value}}</div>

但是我收到了像

这样的错误

Argument 'fn' is not a function, got string

任何想法为什么?

3 个答案:

答案 0 :(得分:5)

这有多个问题。

首先,您在myownservice中的注意没有[,而]并没有正确提供$timeout

接下来,从服务中,您需要通过this访问自己,而不是自己命名。

接下来,您需要从httpcall方法返回承诺,而不仅仅是数字。

这是它应该是什么样子,

angular.module('ngApp', [])

.service('myownservice', ['$q', function($q) {
    this.httpcall = function() {
      var defer = $q.defer();
      var httpresp = "1818";
      defer.resolve(httpresp);
      return defer.promise;
      // replace all this with your $http call and return it..
      // it returns promise itself so you wouldn't need to create on your own
    };

    this.UpdateSomeData = function() {
      return this.httpcall(); 
    };
  }])
  .controller('ctrl', function($scope, myownservice) {
    myownservice.UpdateSomeData().then(function(val) {
      $scope.value = val
    })
  });

working fiddle

答案 1 :(得分:1)

我认为这是一种调用HTTP服务并返回其响应的非常通用的方法。请试试这个

angular.module('ngApp', []).service('myownservice', '$q', function ($timeout, $q) {
    this.UpdateSomeData = function () {
    return $http.get('URL');
};

})

 app.controller('ctrl', function ($scope, myownservice) {
           $scope.value = myownservice.UpdateSomeData(); // Depends on the 
           response, your $scope.value object has to be declared
 });

答案 2 :(得分:0)

你不应该只是回报这样的承诺。试试这样的事情:

$scope.value = myownservice.returnUpdateSomeData ();

你错过了控制器中的myownservice

/rest/task/addAttachmentToNote