【问题标题】:Type casting issue in Observable in Angular 8Angular 8 中 Observable 中的类型转换问题
【发布时间】:2020-07-11 21:55:58
【问题描述】:

您好,我正在学习 Angular 8,作为一名学习者,我有很多疑问。我正在详细分享我的一个疑问。我希望你们中的一些人可以轻松地帮助和纠正我。

我有一个使用 Web API 并返回一些公司详细信息的服务,例如

0: {CompanyId: 1, Name: "xxxx", Address: "bn"}
1: {CompanyId: 2, Name: "yyyy", Address: "tv"}

service.ts

GetAll(): Observable<IEmployee>{
return this.httpClient.get<IEmployee>(this.apiUrl + "GetCompany_test").}

组件.ts

private emp : IEmployee;

getAllEmployees(){
 this.service.GetAll().subscribe(
  response => {this.emp =response;console.log(response)},
  error => console.log(error)
  );}

IEmployee.ts

export interface IEmployee{
fullName:string,
Email:string,
Mobile:string,
City:string,
HireDate:Date
}

即使我使用 Observable&lt;IEmployee&gt; 的 Observable,我也能获得公司详细信息。那么这里有什么需要铸造的呢?当我投射到 Employee 并且我很容易获得非 Employee 数据时,它应该让我在控制台中出现一些警告或错误,对吗?我对正在发生的事情完全感到困惑。

有人可以在这里帮助我理解投射的概念,并建议我正确使用投射。

问候。

【问题讨论】:

  • 能否请您再试一次,将this.httpClient.get&lt;IEmployee&gt;(this.apiUrl + "GetCompany_test") 替换为this.httpClient.get&lt;IEmployee&gt;(this.apiUrl + "GetCompany_test", { "observe": "body" }),看看是否会抛出任何错误?
  • 控制台没有错误。响应还是一样。

标签: angular casting angular-httpclient rxjs-observables


【解决方案1】:

在其他用途​​中进行投射基本上是为了智能感知来帮助您。 当您调用此 get 方法并将IEmployee 类型传递给它时,您基本上是在说,'嘿智能感知,我期待IEmployee 类型的结果。因此,当您订阅结果然后尝试访问它的属性时,它将为您提供IEmployee 中定义的属性。 Intellisense 或get 方法无法预先确定要返回的内容。所以如果你也不知道,你可以传递any 类型,这就像说,'我不知道结果会返回什么类型',所以在这种情况下,你不能得到任何类型检查,因为类型可能是any

现在让我们说,你得到结果,在看到它之后,它看起来就像你已经拥有的 type,所以你可以将它转换为那个类型,然后 Intellisense 可以介入,因为现在它知道类型了。 所以让我们说:

service.ts

GetAll(): Observable<IEmployee>{
return this.httpClient.get<any>(this.apiUrl + "GetCompany_test").}

组件1:

service.GetAll().subscribe(x => {
// x has no type here so no type checking.
// if you call a prop that isn't on it, you will see it at run time
});

//组件2:

service.GetAll().subscribe((x:IEmployee) => {
// x has a type here so there is type checking.
// Intellisense can help you out here
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2020-01-26
    • 2020-08-20
    • 2011-11-17
    • 1970-01-01
    • 2011-11-17
    相关资源
    最近更新 更多