我正在尝试将 API 给出的接口的 JSON 转换为由专用对象组成的不同数组。对象的类型在接口中作为变量给出。
界面:
export interface Interface{
interfaceClassType: string;
}
我正在访问我的 json 数据,如下所示:
getJSON(): Observable<Interface[]> {
return this.http.get<Interface[]>(URL)
.pipe(
retry(2),
catchError(this.handleError)
);
}
这个方法是这样调用的:
arrayWithObjects: Interface[];
class1Array: Class1[];
class2Array: Class2[];
processJSON(): void {
this.configService.getJSON().subscribe(results => this.arrayWithObjects = results);
this.arrayWithObjects.forEach (function (object) {
switch (object.interfaceClassType) {
case "first":
this.class1Array.push(object as Class1);
break;
case "second":
this.class2Array.push(object as Class2);
break;
}
}.bind(this))
}
当我这样称呼它时,我得到了相同的结果:
arrayWithObjects: Interface[];
class1Array: Class1[];
class2Array: Class2[];
processJSON(): void {
this.configService.getJSON().subscribe(results => this.arrayWithObjects = results);
this.arrayWithObjects.forEach ((object) => {
switch (object.interfaceClassType) {
case "first":
this.class1Array.push(object as Class1);
break;
case "second":
this.class2Array.push(object as Class2);
break;
}
})
}
当我执行此方法时,我总是收到一条错误消息:ERROR TypeError: this.class1Array is undefined