2013-01-13 118 views
3

我試圖建立在angularJS一個簡單通知服務:

angular.module("my.services", []) 
    .service("NotificationsService", function() { 

     this.show = function(message, options) { 
      // display a notification 
     }; 

     this.error = function(message) { 
      this.show({...}); 
     } 

     ... 

    }); 

當服務器返回嵌入API一個「通知」陣列將被解僱:

{ 
    notifications: [{type: "error", message: "Error message"}, ...], 
    data: [item1, item2, ...] 
} 

現在我想插入我的服務,以$ HTTP,但我不能找到一種方法,這樣做的!...

任何想法?

回答

8

使用Response interceptor,並注入您的NotificationsService到它:

angular.module("my.services", [], function ($httpProvider) { 

    $httpProvider.responseInterceptors.push(function (NotificationsService) { 

     function notify (response) { 
      angular.forEach(response.notifications, function (obj) { 
       NotificationsService.show(obj); 
      }); 
      return response; 
     } 

     return function (promise) { 
      return promise.then(notify, notify); 
     } 
    }); 

}); 
+0

太好了!謝謝你的幫助 ! :) – TiuSh

+0

太酷了!要命 – iamwhitebox