2

this is login i want get email with 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);
    

this is service i get nothing when i console 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;
  }
...

andi this is header where i want get 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);
    ...

help me to get data from login to header

2 Answers2

2

my friend regarding your example you need to use Subject() in RXJS so then you can get the value from the service without passing it between components.

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

  constructor() { }

  public setEmail(email: string ) {
    this.email.next(session)
  }

  public getEmail(): Observable<string> {
    return this.email.asObservable()
  }
}

Try it this way, I hope it will help you

Manoj Prasanna
  • 156
  • 1
  • 10
  • 1
    prassana i got this in console: Subject {closed: false, currentObservers: Array(0), observers: Array(0), isStopped: false, hasError: false, …} – Yassine Aniba Jul 20 '23 at 10:13
  • you can follow this [passing data in angular](https://stackoverflow.com/questions/49387889/passing-data-with-subjects-and-proxies) – Manoj Prasanna Jul 21 '23 at 05:40
0

You can use BehaviorSubject from rxjs. here is your AuthService

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

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

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

     getemail() {  

         return this.email.asObservable().value;

     }
   
Sathasivam
  • 11
  • 3