如何从角度5中的HttpInterceptor发出事件

时间:2017-11-18 15:51:22

标签: angular events service

我正在尝试从HttpInterceptor发送一个事件。

我的活动服务代码:

import { EventEmitter } from '@angular/core';

export class Message {
    constructor( public name:string, public data:any){    
  }  
}

export class NotifyService {
dispatcher: EventEmitter<any> = new EventEmitter();

constructor() {}

emitMessageEvent(name:string, data:any){
  let message = new Message(name,data);
  this.dispatcher.emit(message);
}

getEmitter() {
  return this.dispatcher;
}

接收事件的组件

import { Component } from '@angular/core';
import { Router } from '@angular/router';

import { NotifyService } from './services/notify.service';


@Component({
  ...
  providers: [ NotifyService ]
})
export class AppComponent {
  subscription: any;

  constructor(private router: Router, private notifyService: NotifyService) {
  }

  ngOnInit() {
    this.subscription = this.notifyService.getEmitter()
      .subscribe(item => this.showAppLevelAlarm(item));
  }

  private showAppLevelAlarm(_notify: any): void {
    // this.message = _notify.msg;
    console.log(_notify);
  }
}

我的HttpInterceptor:

import { NotifyService } from '../services/notify.service';

@Injectable()
export class ApiInterceptor implements HttpInterceptor {

constructor(public notifyService: NotifyService) {}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  return next.handle(req).do(event => {
  return event;
},
error => {
  this.notifyService.emitMessageEvent('showAppLevelAlert', error.error);
})

帮助我理解为什么AppComponent没有收到从HttpInterceptor发送的事件。但是如果我从另一个组件发送一个事件,AppComponent会收到一个事件。

1 个答案:

答案 0 :(得分:0)

你正在解决这个问题,首先,事件发射器不应该是一个观察变化的方法,如

中所述。

http://blog.bogdancarpean.com/how-to-watch-for-changes-an-arrayobject-on-angular-2/

您应该使用localstorage或sessionstorage将数据存储在拦截器中(因为它们本质上是全局的),然后使用Angular中的doCheck生命周期钩子接收对它们的更改

我使用拦截器附加授权令牌并检测我是否应该显示加载栏

这是我的代码

interceptor.ts

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';

@Injectable()
export class IndInterceptor implements HttpInterceptor{
    intercept(
    req: HttpRequest<any>,
    next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).do(evt => {
      localStorage.setItem('loading','Y');
      if (evt instanceof HttpResponse) {
        localStorage.setItem('loading','N');
        console.log('---> status:', evt.status);
        console.log('---> filter:', req.params.get('filter'));
      }
    });

  }
}

component.ts

import { Component, DoCheck } from '@angular/core';
export class AppComponent implements DoCheck{
   public loading; 
   ngDoCheck(){
       this.loading = localStorage.getItem('loading');
       console.log(this.loading);
   }
}