I have a service call that makes a call to an API to return JSON. I then have a function with a subscribe that calls the service call. The JSOON is returned fine and the service call and subscribe all work. However, upon building my application in its build pipeline, I get the following error "Uncaught (in promise) TypeError: Cannot convert undefined or null to object." and my build fails (even though it works fine locally and passes all tests). I am using angular 9 and typescript.
My subscribe and the function that it's in look as such:
houseData: HouseValueObject;
houseNumber = '12345';
callHouseService() {
this.streetHouseService.getHouseData(this.houseNumber).subscribe(
async (data) => {
this.houseData = await data;
const keys = Object.keys(this.houseData.extensiveHouseData);
this.extensiveHouseDataList = keys.map(k => this.houseData.extensiveHouseData[k]);
}
)
}
The getHouseData method looks as such:
export class HouseService {
private readonly relativeURL = 'services/api/houseinfo/'
constructor(private http: HttpClient) {
getHouseData(houseNumber: string): Observable<HouseValueObject> {
return.this.http.get<HouseValueObject>(this.relativeURL houseNumber '/');
}
}
}
The value object for HouseValueObject looks as such:
export class HouseValueObject {
numberBathrooms: number;
extensiveHouseData: HouseValue[];
}
I thought adding the async and await would suspend execution until the returned promise is fulfilled so that the JSON data would be delivered to const keys = Object.keys... line of code would work, but that does not appear to be the case. My question is, how can I correctly go about suspending execution until the returned promise is fulfilled to ensure the JSON data exists and the const keys = Object.keys... line of code works as it does locally?
CodePudding user response:
I personaly would rewrite the service to return a promise, should be easier to read.
HouseService
:
getHouseData(houseNumber: string): Promise<HouseValueObject> {
return this.http
.get<HouseValueObject>(`${this.relativeURL}${houseNumber}/`)
.toPromise<HouseValueObject>();
}
Component
:
async callHouseService(): Promise<void> {
this.houseData = await his.streetHouseService.getHouseData(this.houseNumber);
const keys = Object.keys(this.houseData.extensiveHouseData);
this.extensiveHouseDataList = keys.map(k => this.houseData.extensiveHouseData[k]);
}