使用 forEach() 迭代接口数组
Iterating an interface array with `forEach()`
我是 Typescript 的新手,我想将 HTTP GET 的响应保存到接口定义的类型数组中。
getErrors() {
return this.http.get<ErrorsInterface[]>(environment.apiUrl+'errors').toPromise()
}
然后我像这样声明数组并调用函数getErrors()
errorsData: ErrorsInterface[]= []
this.errorsData = await this.ErrorsService.getErrors()
this.errorsData.forEach(res => {
console.log(res.number)
})
但我收到以下错误:
ERROR Error: Uncaught (in promise): TypeError: this.errorsData.forEach
is not a function TypeError: this.errorsData.forEach is not a function
感谢任何帮助
我认为这里没有必要将可观察对象转换为承诺。你可以用 observable
服务
getErrors(): Observable<any> { // <-- return observable
return this.http.get<ErrorsInterface[]>(environment.apiUrl+'errors');
}
组件
errorsData: ErrorsInterface[]= []
this.ErrorsService.getErrors().subscribe({
next: (res: any) => {
this.errorsData = res;
this.errorsData.forEach(error => {
console.log(error.number)
});
}
error: (error: any) => {
// handle error
}
);
注:
您不能将异步提取转换为同步提取。依赖于异步数据 的任何语句(如 forEach
)必须 位于订阅内。有关异步数据的更多信息 here.
toPromise()
在 RxJS 7 中是 being deprecated 并且在 RxJS
中可能会消失
//in your service file
getErrors():Observable<ErrorInterface[]> {
return this.http.get<ErrorsInterface[]>(environment.apiUrl+'errors')
}
private errorsData= []
getErrors(){
this.ErrorsService.getErrors().Subscribe(res=>
this.errorsData=res
)
//console.log(this.errorsData.length)
}
我是 Typescript 的新手,我想将 HTTP GET 的响应保存到接口定义的类型数组中。
getErrors() {
return this.http.get<ErrorsInterface[]>(environment.apiUrl+'errors').toPromise()
}
然后我像这样声明数组并调用函数getErrors()
errorsData: ErrorsInterface[]= []
this.errorsData = await this.ErrorsService.getErrors()
this.errorsData.forEach(res => {
console.log(res.number)
})
但我收到以下错误:
ERROR Error: Uncaught (in promise): TypeError: this.errorsData.forEach is not a function TypeError: this.errorsData.forEach is not a function
感谢任何帮助
我认为这里没有必要将可观察对象转换为承诺。你可以用 observable
服务
getErrors(): Observable<any> { // <-- return observable
return this.http.get<ErrorsInterface[]>(environment.apiUrl+'errors');
}
组件
errorsData: ErrorsInterface[]= []
this.ErrorsService.getErrors().subscribe({
next: (res: any) => {
this.errorsData = res;
this.errorsData.forEach(error => {
console.log(error.number)
});
}
error: (error: any) => {
// handle error
}
);
注:
您不能将异步提取转换为同步提取。依赖于异步数据 的任何语句(如
forEach
)必须 位于订阅内。有关异步数据的更多信息 here.
中可能会消失toPromise()
在 RxJS 7 中是 being deprecated 并且在 RxJS
//in your service file
getErrors():Observable<ErrorInterface[]> {
return this.http.get<ErrorsInterface[]>(environment.apiUrl+'errors')
}
private errorsData= []
getErrors(){
this.ErrorsService.getErrors().Subscribe(res=>
this.errorsData=res
)
//console.log(this.errorsData.length)
}