无法从angularjs服务设置属性

时间:2015-12-08 20:24:53

标签: angularjs angularjs-scope

我正试图在angularjs控制器的html页面中设置值 我在服务中从web api获得价值,但我遇到的问题是我总是收到错误:

TypeError: Cannot set property 'messageFromServer' of undefined

但我无法弄清楚我在这里做错了什么。我错过了什么? 在html部分我有:

<div ng-app="myApp" ng-controller="AngularController">
     <p>{{messageFromServer}}</p>
</div>

在控制器中我有:

var app = angular.module('myApp', []);
app.controller('AngularController', ['$scope', 'messageService', function ($scope, messageService) {
    $scope.messageFromServer = "When I set it here it works!"
    messageService.getMessage();
}]);

app.service('messageService', ['$http', function ($http) {
    this.getMessage = function ($scope) {
        return $http({
            method: "GET",
            url: "api/GetMessage",
            headers: { 'Content-Type': 'application/json' }
        }).success(function (data) {            
            $scope.messageFromServer = data;            
            console.log(data);
        }).error(function (data) {
            console.log(data);
        })
    };
}]);

2 个答案:

答案 0 :(得分:1)

基本上问题是,您错过了$scope对象服务getMessage方法。但这不是一个好的方法。由于服务是单例对象,因此不应通过将$scope传递给它来直接操作范围。而不是让它尽可能通用,并从那里返回数据。

而是从服务返回promise/data,然后从控制器.then函数将数据分配给范围。

app.service('messageService', ['$http', function ($http) {
    this.getMessage = function () {
        return $http({
            method: "GET",
            url: "api/GetMessage",
            headers: { 'Content-Type': 'application/json' }
        }).then(function (response) {
            //you could have do some data validation here
            //on the basis of that data could be returned to the consumer method
            //consumer method will have access only to the data of the request
            //other information about request is hidden to consumer method like headers, status, etc.
            console.log(response.data);
            return response.data;            
        }, function (error) {
            return error;
        })
    };
}]);

<强>控制器

app.controller('AngularController', ['$scope', 'messageService', 
  function ($scope, messageService) {
    $scope.messageFromServer = "When I set it here it works!"
    messageService.getMessage().then(function(data){
        $scope.messageFromServer = data;
    });
  }
]);

答案 1 :(得分:1)

请勿在您的服务中使用$scope,只需从$http返回承诺。

var app = angular.module('myApp', []);

app.service('messageService', ['$http', function ($http) {
    this.getMessage = function () {
        return $http({
            method: "GET",
            url: "api/GetMessage",
            headers: { 'Content-Type': 'application/json' }
        });
    };
}]);

app.controller('AngularController', ['$scope', 'messageService', function ($scope, messageService) {
    messageService.getMessage().then(function(data) {
      $scope.messageFromServer = data;
    });
}]);

在这个例子中,您可以在控制器中展开承诺,或者甚至可以更好地use the router to resolve the promise并将其注入控制器。

app.config(function($routeProvider) {
  $routeProvider.when('/',{
    controller: 'AngularController',
    templateUrl: 'views/view.html',
    resolve: {
      message: function(messageService) {
        return messageService.getMessage();
      }
    }
  });
});

然后在你的AngularController中,你将有一个未解开的承诺:

app.controller('AngularController', ['$scope', 'message', function ($scope, message) {
    $scope.messageFromServer = message;
}]);