I am trying to broadcast an event from authguard component to my header component.
Broadcast service
@Injectable()
export class BroadcastService {
public subject = new Subject<any>();
sendMessage(message: string) {
this.subject.next(message);
}
}
Receiver (header component)
export class HeaderComponent {
constructor(public broadcast: BroadcastService) {
this.broadcast.subject.subscribe(message => {
alert('broadcast received: ' + message);
});
}
}
Broadcast (authguard component -- doesn't work)
export class AuthGuard implements CanActivate {
constructor(public broadcast: BroadcastService) {
}
canActivate(): boolean {
this.broadcast.sendMessage('Hi from AuthGuard');
return true;
}
}
Broadcast (dashboard component -- works)
export class DashbardComponent {
constructor(public broadcast: BroadcastService) {
}
ngOnInit() {
this.broadcast.sendMessage('Hi from AppComponent');
}
}
app.component.html
<headerComponent></headerComponent>
<router-outlet></router-outlet>
routing
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [AuthGuard]
}
The issue is that when I broadcast from my authguard component, the receiver in my header component never receives the message. I can confirm that the canActivate method in authGuard is called for every path.
But when I broadcast from a page component (eg. dashboard), the receiver in the header component does receive the message.
Does anyone know how to publish a message from the authguard to my header component?