2017-10-14 16 views
1

私の工場ではサービスコールをします。私がその呼び出しから応答を受け取った場合、私は自分のコントローラでアクションを実行したい(つまり、関数doAction()を呼び出す)。 私はいくつかの助けが必要です。私のコードは今働いているので、サービスコールが失敗してもコントローラのアクションを実行します。

サービスコールが失敗すると、コードは工場出荷時のCatchセクションに入りますが、コントローラに戻ってdoAction()メソッドに到達します。

どうすれば避けることができますか?あなたの時間をありがとう、そして可能なばかげた質問を許す。私はAngularにはかなり新しいです。私の工場で

:私のコントローラで

app.factory('myFactory', function ($http) { 
    return { 

     callService: function() { 
      return $http.post("http://xxxxx", {}, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}) 
       .then(function(response) { 
        return response.data; 
       }) 
       .catch(function(response) { 
        console.error(response.status, response.data); 
       }); 
     }, 
    }; 
}); 

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

app.controller('indexController', function($scope, myFactory) { 

    $scope.makeServiceCall = function() { 
     var data = myFactory.callService(); 
     data.then(function (result) { 
      doSomeAction(); 
     }); 
    };  
}); 

答えて

2

例外をキャッチすることによって、あなたが実際にそれを嚥下しているためです。あなたはあなたの工場でエラーをキャッチしないか、次のようにエラーを再現する必要があります:

app.factory('myFactory', function ($http) { 
    return { 

     callService: function() { 
      return $http.post("http://xxxxx", {}, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}) 
       .then(function(response) { 
        return response.data; 
       }) 
       .catch(function(response) { 
        console.error(response.status, response.data); 
        throw response; // <-- rethrow error 
       }); 
     }, 
    }; 
}); 
+0

ありがとうございます。両方のソリューションが機能します! – chichi

2

戻りpromise工場サービスから。

工場:

app.factory('myFactory', function ($http) { 
    return { 

     callService: function() { 
      return $http.post("http://xxxxx", {}, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}});      

    }; 
}); 

コントローラ

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

    app.controller('indexController', function($scope, myFactory) { 

     $scope.makeServiceCall = function() { 
      var data; 
      myFactory.callService().then(function(response) { 
        data = response.data; 
        doSomeAction(); 
       }) 
       .catch(function(response) { 
        console.error(response.status, response.data); 
       }); 
     };  
    }); 
+0

私はこれを試したことがありますかsimularです。私はこれが素晴らしい解決策だと思うので、私はもう一度それを試してみます。 – chichi

+0

@chichiあなたはどんなエラーを出しているのですか? –

関連する問題