Angular 4:HTTP拦截器发射事件到其他组件



我有一个通常的 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>
...

top-navi.component.ts

public onNotify(result: boolean):void {
    console.log('notification received: ' + result);
    this.isLoggedIn = result;
  }

问题在于顶级 - 纳维 - 组件永远不会得到事件,也不会记录任何事件。我在做什么错?

尝试像这样发射值以下步骤

创建新服务文件or如果您有现有服务文件使用

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)
        })
    }
}

相关内容

  • 没有找到相关文章

最新更新