Why is data not being sent to another component using service?

78 Views Asked by At

I have a login component that gets response from database. The response contains many fields and using a service, data goes from one component to another component using getter and setter. But the data is not going between the component even though another component gets the data from that same service's getter.

shared.service.ts :

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SharedService {
  private dataSubject = new BehaviorSubject<any>(null);

  setData(data: any) {
    this.dataSubject.next(data);
  }

  getData() {
    return this.dataSubject.asObservable();
  }
}

login.component.ts :

this.loginService.validateEmployee(formData)
      .subscribe(
        (response:any) => {
          if(response!==null)
          {
            this.sharedService.setData(response);
            this.router.navigate(['/employee']);
          }
        });

myorders.component.ts :

import { Component, OnInit } from '@angular/core';
import { SharedService } from '../shared.service';

@Component({
  selector: 'app-myorders',
  templateUrl: './myorders.component.html',
  styleUrls: ['./myorders.component.css']
})
export class MyordersComponent implements OnInit {
  receivedData:any;
  employeeId:number;

  constructor(private sharedService:SharedService) {}
  ngOnInit(): void {
    this.sharedService.getData().subscribe(data => {
      this.receivedData = data;
      this.employeeId=this.receivedData.employeeId;
    });
  }
}

This is giving employeeId as null. even recievedData is null. But, there is another component, product.component.ts that does this same code and gets the employeeId. why ?

I have tried using different method to store employeeId alone in the same service file but its also not working. Also, I have tried to pass employeeId as parameter from login.component.ts Its also giving null. The Login Component is setting values to shared.service at the initialization and after that, we go to MyOrders Component init to get data. Then, we are not getting the values

0

There are 0 best solutions below