0

HTTP 4xx ステータス コードを検出し、画面上部にアラートを表示するために、インターセプターで呼び出される NotificationService のファクトリを作成しました。アラートはAngularStrap のアラート モジュールを使用します。

app.js

var app = angular.module('app', [
  'app.filters',
  'app.services',
  'mgcrea.ngStrap.alert'
]);

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

app.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
  // Setup all states here…
  $stateProvider
     .state('home')
     .state('about')
     .state('blog');
  // Interceptor
  $httpProvider.interceptors.push("myInterceptor");
});

NotificationService.js

Svc.factory('NotificationService', function($alert) {
  var obj = {};

  // default options for AngularStrap $alert
  var default_options = {
    placement: 'top',
    show: true,
    duration: 3,
    container: 'body'
  }
  obj.error = function(data) {
    angular.extend(default_options, data);  // Merge 'message' property of data into default options
    default_options.type = 'danger';
    $alert(default_options);    // This triggers the alert appearing in the view
  }
  return obj;
});

myInterceptor.js

Svc.factory('myInterceptor', function($q, NotificationService) {
   return {
        responseError: function (response) {
            // Show an alert with the message property in response.data
            NotificationService.error(response.data);

            // do something on error
            return $q.reject(response);
        }
    };
});

私のコードの何かがひどく間違っていますが、どこにあるのかわかりません。AngularStrap のドキュメントを読む$alertと、コントローラー/ディレクティブで使用できるサービスとして公開されていることが言及されています。他の工場で使用しても問題ありませんか?依存関係をどのように含めましたかmgcrea.ngStrap.alert(代わりにapp.services配列にある必要があります)?

正確なエラー メッセージを思い出せません (作業中です) が、エラーはthisを指しています。エラーについて覚えているのは、次のようなものが出力されることです。

$modalProvider <- $alert <- NotifcationService <- <blah blah blah>

これが役立つことを願っています。

4

2 に答える 2