我有一个通常的http intercetor,它调用某个API,如果它收到403响应,必须发出一个事件.
拦截器:
@Injectable export class CustomHttpInterceptor implements HttpInterceptor { @Output() notify: EventEmitter<boolean> = new EventEmitter<boolean>(); constructor() { } intercept(req: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> { if (req.body.status === 403) { this.notify.emit(true); } return next.handle(req); } }
然后我有一个navi.component.html来监听这个事件:
<md-toolbar (notify)="onNotify($event)"> <a routerLink="/home"> <img src="assets/images/logo.png" class="md-card-image p-navi-logo" alt="image caption"></a> <span class="spacer"></span> <div fxLayout="row" fxShow="false" fxShow.gt-sm> <development *ngIf="isLoggedIn"></development> <guide-menu></guide-menu> <documentation-menu></documentation-menu> <administration *ngIf="isAdmin"></administration> <about></about> </div> ...
顶级navi.component.ts
public onNotify(result: boolean):void { console.log('notification received: ' + result); this.isLoggedIn = result; }
解决方法
尝试按照以下步骤发出值
sample.service.ts
@Injectable() export class SampleService { notify: Subject<boolean> = new Subject<boolean>(); onNotify(event) { this.notify.next(true); } }
拦截器:
@Injectable() export class CustomHttpInterceptor implements HttpInterceptor { constructor(private sampleService: SampleService) { } intercept(req: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> { if (req.body.status === 403) { this.sampleService.onNotify(true) } return next.handle(req); } }
和navi.component.html
<md-toolbar> <a routerLink="/home"> <img src="assets/images/logo.png" class="md-card-image p-navi-logo" alt="image caption"> </a> <span class="spacer"></span> <div fxLayout="row" fxShow="false" fxShow.gt-sm> <development *ngIf="isLoggedIn"></development> <guide-menu></guide-menu> <documentation-menu></documentation-menu> <administration *ngIf="isAdmin"></administration> <about></about> </div> </md-toolbar>
最后是top-navi.component.ts
export class TopNaviComponent { constructor(private sampleService: SampleService) { this.sampleService.notify.subscribe((result) => { console.log('result',result) }) } }