需要在视图上显示错误消息,错误消息在控制器中设置

时间:2016-10-28 05:30:33

标签: angularjs

尝试在视图上显示错误消息,当来自控制器的服务调用导致404时,路径被重定向到登录页面视图,并且在$ scope中设置错误消息以在404发生时查看。

下面是控制器代码,它在404发生时在$ scope中设置错误消息

angular.module('app.controllers').controller('contactLoginCtrl',['$rootScope','$scope','AuthenticateService','$location',function($rootScope,$scope,AuthenticateService,$location){


$scope.authenticate =  function(userModel){
    var userName = userModel.username;
    var password = userModel.password;
    console.log(userName+password);
    var result = AuthenticateService.checkUser(userName,password);

    result.then(function(response){
        console.log(response);

    },function(error){

        if(error.status== '404'){

            // ***below is the erroMssg which has to show on the view,
              after setting the message it being redirected to login view***

            $scope.errorMsg = "your request not been processed";
            $location.path('/');
        }
    }) 

};

}]);

在视图中,我将errorMsg表达式设置为{{errorMsg}}

这是行不通的任何人可以建议我锻炼吗?提前谢谢

2 个答案:

答案 0 :(得分:1)

最有可能的是,这是范围摘要周期的问题。这是您的方案的简单工作副本,数据从服务中获取。一旦在ajax错误回调中设置了errMsg,就可以通过使用$ scope.digest()来解决问题。

var app = angular.module("sampleApp", []);

app.controller("sampleController", ["$scope", "sampleService",
  function($scope, sampleService) {

    sampleService.sampleMethod(1).then(function() {
      console.log("Success");
    }, function(error) {
      if (error.status == '400') {
        $scope.errMsg = "Unauthorized User. Please login to continue";
      }
      $scope.$digest();
    });
  }
]);

app.service("sampleService", function() {
  this.sampleMethod = function(value) {
    var promise = new Promise(function(resolve, reject) {
      setTimeout(function() {
        value = value * 2;
        reject({
          status: 400,
          message: "UnAuthorized"
        });
      }, 1000);
    });
    return promise;
  };
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<div ng-app="sampleApp">
  <div ng-controller="sampleController">
    {{errMsg}}
  </div>
</div>

答案 1 :(得分:0)

错误回调将具有单独的范围。所以

angular.module('app.controllers').controller('contactLoginCtrl',['$rootScope','$scope','AuthenticateService','$location',function($rootScope,$scope,AuthenticateService,$location){

$scope.errorMsg = "";
$scope.authenticate =  function(userModel){
    var userName = userModel.username;
    var password = userModel.password;
    console.log(userName+password);
    var result = AuthenticateService.checkUser(userName,password);

    result.then(function(response){
        console.log(response);

    },function(error){

        if(error.status== '404'){

            // ***below is the erroMssg which has to show on the view,
              after setting the message it being redirected to login view***

            $scope.errorMsg = "your request not been processed";
            $location.path('/');
        }
    }) 

};