0

I'm trying to pass the object to object Model using a shared service to a already loaded component , even though i get data after subscription, it is not reflecting in html view.

<div *ngFor="let emp of emps" class="card">
      <div class="card-body">
            <img class="img-icon" [src]="emp?.logo" />
                </div>
      <div class="icon-text">
      <p class="maintext" >{{emp?.name}}</p>
      <p class="subtext">Emp Code: {{emp?.code}}</p>
       </div>
                   
       <div class="icon-text">
             <a class="view-btn" >View Details</a>
       </div>
  </div>
emps : EmployeeModel[];


ngOnInit(): void {

    this.service.getData().subscribe(data => {
      this.emps = data
      console.log(this.emps))
    })
   }

export class EmployeeService {
  employeeData:any;
  private subject = new Subject<any>();
  constructor() { }
  
  setEmployeeData(data) {
    this.employeeData = data
    this.subject.next(data);
  }

 getData(): Observable<any> {
    return this.subject.asObservable();
 }
} 

  
BLU
  • 61
  • 8
  • Because the response is probably asynchronous. You can trigger change detection manually https://stackoverflow.com/a/42695581/310726 – martin Feb 07 '22 at 11:42
  • i tried it, but this isn't solving the issue – BLU Feb 07 '22 at 11:53

2 Answers2

1

Use BehaviorSubject instead of Subject

private subject = new BehaviorSubject<any>(null);
zainhassan
  • 1,684
  • 6
  • 12
0

The observable being returned from getData() isn't emitting anything. That is until you invoke setEmployeeData() with data.

Joshua McCarthy
  • 1,739
  • 1
  • 9
  • 6
  • I have already invoked `setEmployeeData()` after that i'm trying to invoke `getData()` – BLU Feb 07 '22 at 11:52
  • Invoking `setEmployeeData()` is missing from your example. Anyway, try the opposite order. First set your subscription, then invoke the new data value. – Joshua McCarthy Feb 07 '22 at 11:54