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

now*_*ed. 1 javascript angularjs angular-promise

这是我用来学习角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();
 });
Run Code Online (Sandbox Code Playgroud)

html page:

<div ng-controller="ctrl">{{value}}</div>
Run Code Online (Sandbox Code Playgroud)

但我收到的错误就像是

Argument 'fn' is not a function, got string.

有什么想法吗?

tan*_*may 5

这有多个问题.

首先,您在注射myownservice了没有[,并]$timeout未正确设置.

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

接下来,您需要从httpcall方法返回一个promise ,而不仅仅是number.

这是它应该是什么样子,

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
    })
  });
Run Code Online (Sandbox Code Playgroud)

工作小提琴

  • 我们走了,这是正确的答案.好的,你还清理了`UpdateSomeData`的延迟反模式. (2认同)