-1

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;
    }
  )
Moonket
  • 11
  • 6
  • Does this answer your question? [How to share data/change between components](https://stackoverflow.com/questions/35878160/how-to-share-data-change-between-components) – The Fabio Dec 23 '21 at 21:26
  • I have seen this asked in many different ways, here was my answer to it: https://stackoverflow.com/a/68705626/4604645 – The Fabio Dec 23 '21 at 21:27

3 Answers3

0

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

Some random IT boy
  • 7,569
  • 2
  • 21
  • 47
0

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='';
0

Use state management and event driven arhcitecture for your app. Mutate the application state, subscribe to events in component/service classes.

Create an action to modify your store state from anywhere in your app.

Expose a stream (selector) via your store state, then consume it in any other classes you want.

For instance, you can create an events module: events.module.ts, events.state.ts, events.interface.ts, events.actions.ts.

rfprod
  • 231
  • 2
  • 8