Reputation: 83
I can't figure out what am I doing wrong, But after making a call to an API, I receive the proper response, but I try to push the response to the array I have. but it returns Undefined.
export interface CustomerInfo {
firstName: string;
middleName: string;
lastName: string;
dateOfBirth: Date;
}
// if the info comes form parent or not
@Input() customerInfo?: CustomerInfo []=[];
// references would be an array of sting, containing 2 id number, somthing like below:
refrences = ["jack1","ana12"]
// the getCustomerInfo called on ngOnInit like below:
ngOnIit() {
//check if indeed the customerInfo is empty
if (!this.customerInfo) {
this.getCustomerInfo()
}
}
getCustomerInfo() {
for (let reference of references) {
this.customerService.getCustomerInfo(reference).subscribe(
value => {
console.log("customer info ", this.customerInfo)
console.log("this value ", value)
this.customerInfo.push(value)
}, error => {
console.log(error);
}
)
}
#Update: the issue is the value is log correctly which means I receive the correct response, but the customer info log is undefined. and I don't know why?! The this log includes customerInfo which the value is undefined,
Upvotes: 0
Views: 3019
Reputation: 83
The issue was here on ngOnInit
, which I had to check if this.customerInfo
is Null or undefined; if so, before making a call to the getCustomerInfo
API, simply make the customer info equal to an empty array, so that when we get the response back from the call, we can push our response to the array:
ngOnIit() {
if (!this.customerInfo?.length) {
this.customerInfo = []
this.getCustomerInfo()
}
}
Upvotes: 1