加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 4:http拦截器向其他组件发出事件?

发布时间:2020-12-17 17:29:39 所属栏目:安全 来源:网络整理
导读:我有一个通常的http intercetor,它调用某个API,如果它收到403响应,必须发出一个事件. 拦截器: @Injectableexport class CustomHttpInterceptor implements HttpInterceptor { @Output() notify: EventEmitterboolean = new EventEmitterboolean(); construc
我有一个通常的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;
  }

问题是top-navi-component永远不会获取事件并且不记录任何内容.我究竟做错了什么?

解决方法

尝试按照以下步骤发出值

创建新的服务文件,或者如果您有现有的服务文件使用它

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

    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读