gpt4 book ai didi

Angular 4 : http interceptor emit events to other components?

转载 作者:太空狗 更新时间:2023-10-29 17:47:59 24 4
gpt4 key购买 nike

我有一个常用的 http 拦截器,它调用某个 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;
}

问题在于 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)
})

}
}

关于 Angular 4 : http interceptor emit events to other components?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47714984/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com