Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular8 当尝试使用json深度为2+的rest Api时,如何解决typescript中的类型兼容性问题;_Angular8 - Fatal编程技术网

Angular8 当尝试使用json深度为2+的rest Api时,如何解决typescript中的类型兼容性问题;

Angular8 当尝试使用json深度为2+的rest Api时,如何解决typescript中的类型兼容性问题;,angular8,Angular8,我试图使用从本地服务器发送的Rest Api,使用homestead将其显示到我的angular应用程序中,虽然请求已成功发送,如图所示,但问题是每当我尝试显示它时,它都表示未定义,我认为问题是因为我有json deapth 2+,类型脚本可能不知道对象类型 我尝试过反序列化,但没有成功 OwnerClass.ts 从“/Acommodation”导入{Acommodation}; 从“/Taxi”导入{Taxi}; 从“/car rent”导入{CarRent}; 导出类所有者{ id?:字符

我试图使用从本地服务器发送的Rest Api,使用homestead将其显示到我的angular应用程序中,虽然请求已成功发送,如图所示,但问题是每当我尝试显示它时,它都表示未定义,我认为问题是因为我有json deapth 2+,类型脚本可能不知道对象类型

我尝试过反序列化,但没有成功

OwnerClass.ts

从“/Acommodation”导入{Acommodation};
从“/Taxi”导入{Taxi};
从“/car rent”导入{CarRent};
导出类所有者{
id?:字符串;
cin:字符串;
名称:字符串;
电子邮件:字符串;
电话:字符串;
住宿:住宿[];
出租车:出租车[];
汽车租赁:CarRent[];
}
acomodationclass.ts

从“/Owner”导入{Owner};
出口类商品{
id?:字符串;
业主:业主;
描述:字符串;
容量:字符串;
床:细绳;
浴缸:绳子;
可用性:布尔值;
大奖赛之夜:浮动阵列;
地址:字符串;
图片:字符串;
}
myComponent.component.ts

从'@angular/core'导入{Component,OnInit};
从“../Services/restapi Owner.service”导入{RestApiService};
从“../Classes/Owner”导入{Owner};
@组成部分({
选择器:“应用程序网格”,
templateUrl:'./grid.component.html',
样式URL:['./grid.component.css']
})
导出类GridComponent实现OnInit{
业主:业主[];
构造函数(私有restApiOwner:RestApiService){}
恩戈尼尼特(){
this.restApiOwner.getOwners().subscribe(Owners=>this.Owners=Owners);
console.log(this.owners);
}
}
这将证明RESTAPI可以工作并返回Json


未定义的结果

问题是由于这两行的位置:

this.restApiOwner.getOwners().subscribe(Owners=>this.Owners=Owners);
console.log(this.owners);
让我们假设从
getowner()
调用返回数据需要整整5秒钟,在此期间javascript不会等待数据返回。同样地,
console.log(this.owners)
将在订阅调用“设置”后立即执行,其中
this.owners
仍然没有被分配,因此将打印出
未定义的
。您可以通过使用devtools使您的网络非常慢来看到这一点,并注意到
未定义的打印输出几乎会立即打印出来,即使网络调用没有返回任何内容

与JavaScript/TypeScript的任何异步操作一样,需要执行“回调”元素。在JS作为单线程的情况下,不存在等待这样的事情,而且不能等待

以下方法可用于处理异步回调:

  • -老派做法
  • -更常见的方法,更容易链接
  • -对承诺采用不同的“语法糖”方法,这使代码看起来像是在“等待”,但事实并非如此
  • -角度观测由rxjs库处理,基本上是类固醇承诺
由于Angular提供了rxjs来处理异步代码,并且您已经在使用它,因此我建议您将代码更改为以下内容:

this.restApiOwner.getOwners().subscribe(Owners=>{
这个。所有者=所有者;
console.log(this.owners);
});
这是因为日志将在数据返回后打印。从技术上讲,您的代码一直在工作,但是console.log只是在错误的位置,并且在错误的时间运行

最后,我建议阅读更多关于JS如何处理异步操作的内容,因为它是该语言的关键基础。这是关于这个话题的最新消息