0

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

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

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

服务.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 的Observable<IEmployee>. 那么这里有什么需要铸造的呢?当我投射到 Employee 并且我很容易获得非 Employee 数据时,它应该让我在控制台中出现一些警告或错误,对吗?我对正在发生的事情完全感到困惑。

有人可以帮我理解铸造的概念,并建议我正确使用铸造。

问候。

4

1 回答 1

1

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

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

服务.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
});
于 2020-03-31T11:16:34.260 回答