How can I emit a string value across unrelated components in Angular? I have a login component in which when the user successfully logs in to my backend API, the HTML response will include their username. I then want this username to be emitted to a seperate profile component.
The emitter is defined in its own class:
import { EventEmitter } from "@angular/core";
export class Emitters{
static messageEmitter = new EventEmitter<string>();
The login method:
onLogin() {
const usn = this.loginForm.get('username').value;
const pwd = this.loginForm.get('password').value;
this.http.post('http://localhost:5000/api/v1.0/login', null, {
headers: new HttpHeaders({
Authorization: `Basic ${btoa(`${usn}:${pwd}`)}`
})
}).subscribe((_response: any) => {
console.log(_response);
this.loginForm.reset();
this.username = (_response.username);
Emitters.messageEmitter.emit(this.username);
});
}
And the function to subscribe to the emitter within the profile component:
Emitters.messageEmitter.subscribe(
(username: string) => {
this.username = username;
}
)