Home > Software engineering >  Cannot Show BehaviorSubject Variable in view in Angular
Cannot Show BehaviorSubject Variable in view in Angular

Time:07-16

I have created this service

Service File :

InfoDetails=new BehaviorSubject<any>('');

getsInfo(data: any): Observable<any> {
    return this.http.post<any>(`${environment.url}/Info`, data)
}

In component 1:

 ngOnInit(): void {
    this.getInfo(this.UserId);
 }
 InfoList: any;
 getInfo(userId)
  { 
  this.Service.getsInfo(json).subscribe(data => {
  if (data.response == 200) {
    this.InfoList = data.response;

    let jsons=[
      {
          "Id": 2,
          "Name": "Test",
          "Email": "[email protected]",
          "Code": 4346
      },
      {
          "Id": 2,
          "Name": "Test",
          "Email": "[email protected]",
          "Code": 4346
      }
     ];

    this.Service.InfoDetails.next(jsons);
   
  }
})
  }

In Component 2:

 let jsons=[
          {
              "Id": 4,
              "Name": "Test 1",
              "Email": "[email protected]",
              "Code": 43246
          },
          {
              "Id": 67,
              "Name": "Test 3",
              "Email": "[email protected]",
              "Code": 3336
          }
         ];

    this.ChatService.chatInfoDetails.next(jsons);

Issue is how will i loop through variable in component 2 so that if variable value changes it should automatically reflect in the component immediately without page refresh.

Any suggestion is highly appreciated Thanks

CodePudding user response:

When you want to render in HTML, you can just do the following.

Add a getter for the Subject. But I strongly advice, you convert the subject to an observable as shown below.

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

@Injectable()
export class ChatService {
  InfoDetails = new BehaviorSubject<any>('');
  InfoDetailsObservable$: Observable<any>;

  getsInfo(data: any): Observable<any> {
    return this.http.post<any>(`${environment.url}/Info`, data);
  }
  constructor() {
    this.InfoDetailsObservable$ = this.InfoDetails.asObservable();
  }
}

Then in component 2 you can create the getter as below.

get infoDetails() {
    return this.ChatService.InfoDetailsObservable$;
}

Finally in component 2 html you need to use the async pipe and render the latest values of the behaviour subject!

<section >
  <div >
    <pre *ngIf="!(infoDetails | async)">loading objectives...</pre>
    <span *ngFor="let test of infoDetails | async">{{ vehicle.Name }}</span>
  </div>
</section>
  • Related