There seems to be an issue with transferring data between components in Angular

For the login feature, I am looking to receive an email using two-way databinding.

...
export class LoginComponent implements OnInit {
  author ={
    email:'',
    password:''
  }
  constructor(private _auth: AuthService, private router: Router) { }

  ngOnInit(): void {
    
  }

  token : any;
  login(){
    let sendEmail = this.author.email
    this._auth.setemail(sendEmail);
    console.log(sendEmail);
    

In the service, I am not getting any output when I try to log the data in getemail.

...
@Injectable({
  providedIn: 'root'
})
export class AuthService {
  
  serEmail= ''

  setemail(data: string) {
    this.serEmail= data;
    console.log(this.serEmail);
    
  }

  getemail() {
    let data = this.serEmail
    console.log(data);
    return data;
  }
...

Additionally, in the header component, I aim to retrieve this data.

...
export class HeaderComponent implements OnInit {
  data2: any
  id: any
  recEmail:any;
  constructor(public _auth: AuthService) { }
  
  ngOnInit(): void {
    this.recEmail = this._auth.getemail();
    console.log(this.recEmail);
    ...

I need assistance in transferring the data from the login component to the header component.

Answer №1

Hey there! If you want to access the value from a service without passing it between components, consider using Subject() in RXJS. Here is an example code snippet for you:

@Injectable({
  providedIn: 'root'
})
 export class DataService{
  public data = new Subject<string>();

  constructor() { }

  public setData(value: string ) {
    this.data.next(value)
  }

  public getData(): Observable<string> {
    return this.data.asObservable()
  }
}

Give it a try and see if it works for your requirements. Good luck!

Answer №2

To implement a functionality in your application, you can utilize the BehaviorSubject feature provided by rxjs library. Below is an example demonstrating how you can integrate it into your AuthService:

    ...
      private emailAddress: BehaviorSubject<any> = new 
  BehaviorSubject<any>(null); 

    @Injectable({
      providedIn: 'root'
    })
    export class AuthService {

     userEmail= ''
     setEmail(data: string) {
        this.userEmail= data;
        this.emailAddress.next(this.userEmail);
        console.log(this.userEmail);
      }

     getEmail() {  

         return this.emailAddress.asObservable().value;

     }
   

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with Angular 2 HTTP functionality

Currently, I am utilizing Angular 2 beta.18 and attempting to implement Google Map geocode functionality. Despite following all available tutorials, the response I receive is quite peculiar. Below is my component code: import { Injectable } from '@a ...

Generating React Components Dynamically using TypeScript

Attempting to generate an element in React using Typescript based on the given tagName passed as props, along with additional relative element properties depending on that particular tagName. Take a look at the code snippet below: type ElementProps<Tag ...

Include the complete path to the base href within an Angular application

How can I retrieve the base href in Angular, including the domain (or subdomain)? Here is a use case: I need to add the og:image property using the Meta service. The current content shows as /image.jpg, but I want it to display as https://example.com/ima ...

Error: The property you are trying to destructure is undefined, please define it before destructuring

I'm struggling to render the 'password confirmation input' and the 'button', as it's not working at all. I'm unsure of what changes need to be made. TypeError: Cannot destructure property '' of '' sinc ...

Encountering issues with Bootstrap functionality

I am currently working on an Angular 4 application. After installing both Bootstrap 4 and NG Bootstrap using the following commands: npm install --save bootstrap npm install --save @ng-bootstrap/ng-bootstrap I have updated my package.json file with the ...

Guide on activating a tab programmatically in Kendo UI for Angular 2

I'm looking to activate a tab in Kendo UI angular 2 TabStripComponent using the selectTab method from my TypeScript code. Can anyone provide guidance on how to achieve this? ...

NgZone is no longer functioning properly

Seemingly out of the blue, my NgZone functionality has ceased to work. I'm currently in the process of developing an application using Ionic, Angular, and Firebase. An error is being thrown: Unhandled Promise rejection: Missing Command Error ; Zon ...

Implementing a dynamic star rating system in Angular

I am working with an array of ratings that looks like this: "rating": [ { "sno": 1, "question": 13, }, { "sno": 2, ...

What strategy does Node recommend for organizing code into multiple files?

In the midst of my current project, which involves NodeJS and Typescript, I am developing an HTML5 client that communicates with a NodeJS server via web-sockets. With a background in C#, I prefer to organize my code into separate files for different functi ...

Which is the better choice for simply invoking a service method - subscribe or toPromise?

When implementing the search method below, I simply assign the value of BehaviourSubject in the service. However, I am unsure whether it is possible to execute this operation without using either subscribe() or toPromise() after the .pipe() block in the ...

Tips for accessing and adjusting an ngModel that is populated by an attribute assigned via ngFor

Looking for guidance on how to modify an input with ngModel attribute derived from ngFor, and update its value in the component. Here is my code snippet for reference: HTML FRONT The goal here is to adjust [(ngModel)] = "item.days" based on button click ...

There seems to be an issue with Angular 8's *ngIf not correctly updating the UI in the navigation bar

I am currently working on integrating bootstrap@4 with an Angular 8 application to ensure full responsiveness. In the navigation bar, certain elements such as the logout button or link should be hidden if the user is not registered or logged in, and vice ...

Retrieve all documents from the service and controller by utilizing pouchdb

Having trouble retrieving data from my service and controller, I am now looking to incorporate CRUD functionality into my web applications. Below is the code for my service: application.service('Arrears', [ function() { var db = new PouchDB ...

What is the best way to horizontally align an Angular mat-expansion-panel?

I have exhausted all my ideas trying to make this work. I made some changes to a different stackblitz as a test: https://stackblitz.com/edit/angular-acdxje-8bz7tq?file=app%2Ftable-basic-example.html,app%2Ftable-basic-example.css,styles.css,app%2Ftable-bas ...

Recording changes in SVG size in Angular 2

I am aiming to create an SVG canvas within an Angular 2 template that automatically scales with its parent element and triggers a redraw method when its size changes. While using the onresize property, I successfully receive events but encounter difficult ...

Using ngClass to merge two types of expressions

I am attempting to merge two different expression types using ngClass so that they are binded to the data and updated with changedetection as shown below: <div [ngClass]="[test.value | myClassPipe, {'anotherClass': test.isValid}]"></div ...

Error message: "Vue3 JSX files are throwing a ReferenceError because React is not defined."

Currently, I am working on integrating storybook with antdv. However, when importing a tsx file that contains jsx within the button.stories.js file, I encountered an error stating "ReferenceError: React is not defined". You can view the error here. It is i ...

Components within Angular components

Can an Angular component be created to accept the following structure: <app-parent> <app-child>Option 1</app-child> <app-child>Option 2</app-child> </app-parent> This component would then parse and handle this struct ...

Creating a State in Typescript Vuex with Accessors: A Step-by-Step Guide

Within the vuex store, I am attempting to initialize a state called _token. However, when I try to access the property within the same class, I am encountering an error message stating that the setter for _token is not defined. Can anyone shed light on why ...

Using TypeScript's interfaces to push items

Can anyone provide some guidance on working with interfaces in typescript? I currently have the following 3 interfaces: export interface HomeMenu { [name: string]: MenuItem; } export interface MenuItem { title: string; route: string; hom ...