HttpInterceptor에서 이벤트를 보내려고합니다. 내 이벤트 서비스의각도 5의 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);
})
나를 이해하는 데 도움을 이유에서 전송 된 이벤트 HttpInterceptor는 AppComponent에 의해 수신되지 않습니다. 그러나 다른 구성 요소에서 이벤트를 보내면 AppComponent가 이벤트를 수신합니다.