javascriptangularrxjsobservablesubject-observer

display async data in the angular view


i am fetching the data form an API beck-end and displaying its content in to my view in angular,

for the service i am using observables

export class PropertyService {
  apiUrl: string = environment.domain;

  constructor(private http: HttpClient) {}

  private _propertyDetailedInfo = new Subject();
  propertyDetailedInfo$: any = this._propertyDetailedInfo.asObservable();
  updatePropertyDetailedInfo(data: any) {
    this._propertyDetailedInfo.next(data);
    this.propertyDetailedInfo$ = data;
  }


  gerPropertyDetailedInfo(id: string) {
    const res = this.http.get(`${this.apiUrl}/property?id=${id}`);
    res.subscribe((val) => {
      this.updatePropertyDetailedInfo(val);
      console.log(this.propertyDetailedInfo$);
    });
  }
}

and i am subscribing to it in the Component

export class PropertySpecsComponent implements OnInit {
  propertyInfo!: any; 
  constructor(private propertyService: PropertyService) {}
  ngOnInit() {
    
    this.propertyService.gerPropertyDetailedInfo('90949d476fb');
    this.propertyService.propertyDetailedInfo$.subscribe((res: any) => {
      this.propertyInfo = res;
      console.log(
        ` flexibleCancellation : ${this.propertyInfo.flexibleCancellation}`
      );
    });
  }
}

the console.log works and displays what i am looking and even can be displayed in the view with the pipe i am getting the value of TRUE for but is cant red the in ng-for

enter image description here

the code for it:

enter image description here

error i am getting:

enter image description here

i trayed to insert the data-object staticly and stored it in service (i did not use observebols) that works displaying the data using json pipe aslo works {{ propertyInfo.flexibleCancellation | json }}

but not for *ngIf="propertyInfo.flexibleCancellation"

using aysinc pipe dos not work for me

*ngIf="propertyInfo.flexibleCancellation | async" i get: 

enter image description here


Solution

  • using optional chaining is a solution no need to use async pipe

    *ngIf="propertyInfo?.flexibleCancellation"