Reputation: 4050
I have a usual http intercetor
, that makes a call to a certain API and if it receives a 403
response, must emit an event.
Interceptor:
@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);
}
}
And then I have a navi.component.html
that would listen for this event:
<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;
}
The problem is that the top-navi-component never gets the event and doesn't log anything. What am I doing wrong?
Upvotes: 6
Views: 3882
Reputation: 11184
Try like this to emit value follow below steps
create new service file or
if you have existing service file use that
sample.service.ts
@Injectable()
export class SampleService {
notify: Subject<boolean> = new Subject<boolean>();
onNotify(event) {
this.notify.next(true);
}
}
Interceptor:
@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);
}
}
and 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>
finally top-navi.component.ts
export class TopNaviComponent {
constructor(private sampleService: SampleService) {
this.sampleService.notify.subscribe((result) => {
console.log('result', result)
})
}
}
Upvotes: 10