简体   繁体   中英

unable to pass data between one component to another component in angular

I am trying to pass data from one component to another component I used the service file method. I created two components one is login and the second is home. I have to pass data from login to home. in the login component, I take user input, and the home component should print that. I used this code below, but when I give input, it is not printing in output.

 import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class SharedService { message : any; constructor() { } setMessage(data: any){ this.message=data; } getMessage(){ return this.message; } }
this is my home component code
 import { Component, OnInit } from '@angular/core'; import { SharedService } from '../shared/shared.service' @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { message : string | undefined; constructor(private shared:SharedService ) {} ngOnInit() { this.message =this.shared.getMessage() } }
 <h1> {{ message }} </h1>
this is my login component code
 import { Component, OnInit } from '@angular/core' import { SharedService } from "../shared/shared.service" @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { message : any ; constructor( private shared: SharedService ) { } ngOnInit(): void { this.shared.setMessage(this.message) } }
 <input required type="text" class="form-control" placeholder="Enter username" [(ngModel)]="message">

ofcourse it will not work this way .the reason it is not working . when you call SharedService in your constructor in box component it create an instance of your service with message : any . if you change it on one component it will not change on the other component .

what you can do is . on your service . message = new Subject() ; setMessage(data: any){ this.message.next(data) ; } message = new Subject() ; setMessage(data: any){ this.message.next(data) ; } you call set message on your login component . and on your home component you subscribe to the subject like this . this.sharedService.getMessage().subscribe( (result :any ) => {console.log(result )} .

sorry if this answer is messy , this is my first time using SOF .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM