在哪里写成功和错误



在这里我使用的是angularjs1.x,这是我的状况。如果条件成功,请显示表格,否则会丢下错误。我知道一些代码是否成功。

angctrl.js

 $scope.BtnCall = function () {
  ServiceCntrl.CallData().then(function (d) {
        $scope.EmpData = d.data;
    });
 }      

angservice.js

eApp.service("ServiceCntrl", function ($http) {
var xx = '';
xx= $http({
        data: formData,
        method: 'post',
        url: Url,
        datatype: "json"
    }).success(function (rsp) {
        RspData = rsp;
        return RspData;
    }).error(function (rsp) {
        console.log('Error');
    });
    return xx;
};

您的x.then接收两个函数x.then(function(){}, function(){});在成功解决承诺时,请调用第一个功能,如果拒绝承诺(失败),则调用第二个功能。

如果您的服务功能返回$ HTTP Promise,则您的第一个功能可以具有命名的参数(您喜欢的任何内容),并且它将具有您可以使用的响应数据。第二个功能可以接收错误参数,如果有。

您应该查看Angular $ http服务文档。

如果您的服务正在返回Get请求的承诺,则可以写

$scope.BtnCall = function () {
    var x = ServiceCntrl.CallData();
    x.then(function(response) {
   //Success callback
   //code on success goes here
   //response.data
  }, function(response) {
    //error callback
    //code on error goes here
    // server returns response with an error status.
  });

您可以使用ng-show/ng-hide在HTML页面上显示和隐藏内容。

您可以写下成功/失败代码如下:

$scope.BtnCall = function() {
   var x = ServiceCntrl.CallData();
   x.then(function(result) {
       // Success code here 
       // Do something and resolved the promise           
   }, function(reason) {
       // Error code here
       // You may handle/reject the reason in params
   });
});

另请参见$q的角文档。

angularjs $ http服务向服务器提出请求,并返回响应
上面的示例用对象作为参数执行$ HTTP服务。该对象正在指定HTTP方法,URL,成功做什么以及在失败上做什么。

 $scope.BtnCall = function () {
      ServiceCntrl.CallData().then(function (d) {
            $scope.EmpData = d.data;
        });
     }    

angservice.js:

  eApp.service("ServiceCntrl", function ($http) { 
    var xx = '';
    xx= $http({ 
             data: formData,
             method: 'post',
             url: Url, 
             datatype: "json" 
           }).success(function (rsp) {
              RspData = rsp; 
              return RspData; 
          }).error(function (rsp) { 
            console.log('Error');
           });
         return xx; 
    };

最新更新