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;
}
)
CodePudding user response:
Use a service provided in the AppModule
as @Injectable({providedIn: 'root'})
and expose a Subject
, Observable
or BehaviorSubject
. To choose the right one for your use-case you should take a read to the RxJS docs
Then include the service through dependency injection and subscribe to that singleton source of events
CodePudding user response:
An event emitter is a pattern that listens to a named event, fires a callback, then emits that event with a value.
import { EventEmitter } from "@angular/core";
In Child Component's Html:
<button (click)="FileEvent()">Send Message</button>
In Child Component's Ts:
@output() public childEvent=new EventEmitter()
FileEvent()
{
this.childEvent.emit('Hello');
}
In Parent Component's Html:
<app-child (childEvent)="Message=$event" ></app-child>
In Parent Component's Ts:
public Message='';