2017-11-14 13 views
0

私のイオンプロジェクトでは、ファイルがローカルに存在するかどうかを調べる機能を作成しています。私は次の関数を作成しました:角度:ファイルが見つかりませんでした404エラーをキャッチ

$rootScope.eventFieldTemplateExists = function(field) { 
    //var templateUrl = 'views/fields/' + field.name + '.html'; 
    var templateUrl = 'views/fields/testfile.html'; 


    $http.head(templateUrl).then(function(res) { 
     console.log("success"); 
     console.log(res); 
    }) 
    .catch(function(err) { 
     console.log("catch"); 
     console.log(err); 
    }); 

    return true; 
}; 

ファイルtestfile.htmlは存在しません。

HEAD http://localhost:9000/views/fields/testfile.html 404 (Not Found) 
catch 
{data: "", status: 404, config: {…}, statusText: "Not Found", headers: ƒ} 

エラーを抑制するためのいくつかの方法があります:私は存在しないファイルを入力しますが、ファイルが存在しない場合、私はまだコンソールのエラーを取得する時には、上記正常に動作しますか?私は.catchがそれを抑制することを望んでいましたが、明らかにそうしていません。

+0

、なぜあなたは 'HTTP head'を使用している、それはレスポンスボディなしで応答します。代わりに 'http get'を使用しました –

+0

なぜコンソールからHTTPエラーを取り除きたいのですか? – Zooly

答えて

0

ステータスが404の応答では、約束の拒否ハンドラが呼び出されますが、これは予想される動作ですが、コードには含まれていないため、制御は.catchになります。

はあなたがthen()のための二番目のパラメータで$http要求のすべてのエラーをキャッチすることができ拒否ハンドラを含めると、応答に.when

$http.head(templateUrl).then(function(res) { 
    // this will run for status 2xx 
    console.log("success"); 
    console.log(res); 
}, function(response) { 
    // this will run for status 4xx, 5xx, etc.. 
    if (response.status === 404) { 
     return $q.when("404: file not found, but it's ok") 
    } 
    return $q.reject(response); 
}) 
.catch(function(err) { 
    console.log("catch"); 
    console.log(err); 
}); 
0

を解決します。このように動作します$http.head

$http.head(templateUrl).then(function(res) { 
    console.log("success"); 
    console.log(res); 
}, function(err) { 
    console.log("catch"); 
    console.log(err); 
}) 

AngularJs:

$http.head('/someUrl', config).then(successCallback, errorCallback); 

Documentation on $http

離れエラーから
関連する問題