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
the code for it:
error i am getting:
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:
3
Answers
using optional chaining is a solution no need to use async pipe
Problem Analysis
Probably the view of your component is rendered before the response of the observable is emitted. At that time the proprerty
propertyInfo
is undefined as it does not have an initial value. In your template the call offlexibleCancellation
onpropertyInfo
leads to a javascript error, becasuepropertyInfo
is not yet defined.Possible Solutions:
1- Use optional Chaining like in ibrahimgb’s answer
*ngIf="propertyInfo?.flexibleCancellation"
2- Wrap the part of the template that depends on
propertyInfo
in an*ngIf
And display a loading spinner if the property is undefined
3- Set an empty object as initial Value for
propertyInfo
The view is getting rendered before the value of your
propertyInfo
variable is set. Checking whether that value is undefined using*ngIf
will solve the issue hopefully.