如何正确地附加到打字稿中的数组?
How correctly append to an Array in typescript?
我不知道我做错了什么,但是在调用 API 之后,我收到了正确的响应,但我尝试将响应推送到我拥有的数组。但它 returns 未定义。
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);
}
)
}
#更新:
问题是值是正确记录的,这意味着我收到了正确的响应,但客户信息日志未定义。我不知道为什么?!
此日志包含值未定义的 customerInfo,
问题出在 ngOnInit
,我必须检查 this.customerInfo
是 Null 还是未定义;如果是这样,在调用 getCustomerInfo
API 之前,只需将客户信息设为一个空数组,这样当我们从调用中得到响应时,我们可以将我们的响应推送到数组:
ngOnIit() {
if (!this.customerInfo?.length) {
this.customerInfo = []
this.getCustomerInfo()
}
}
我不知道我做错了什么,但是在调用 API 之后,我收到了正确的响应,但我尝试将响应推送到我拥有的数组。但它 returns 未定义。
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);
}
)
}
#更新: 问题是值是正确记录的,这意味着我收到了正确的响应,但客户信息日志未定义。我不知道为什么?! 此日志包含值未定义的 customerInfo,
问题出在 ngOnInit
,我必须检查 this.customerInfo
是 Null 还是未定义;如果是这样,在调用 getCustomerInfo
API 之前,只需将客户信息设为一个空数组,这样当我们从调用中得到响应时,我们可以将我们的响应推送到数组:
ngOnIit() {
if (!this.customerInfo?.length) {
this.customerInfo = []
this.getCustomerInfo()
}
}