0

Hi I am learning Angular 8 and as a learner I have many doubts. I am sharing one of my doubts in detail. I hope some of you can easily help and correct me.

I have a service which consumes to Web API and returns some company details like

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").}

component.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
}

I get the company details even though I use Observable of Observable<IEmployee>. So what is the need of casting here? and when I cast to Employee and I easily get non Employee data,it should so me some warning or error in the console right? I am totally confused about what is happening.

Can somebody please help me to understand the concept of casting here and advice me to correctly use casting.

Regards.

vivek v
  • 167
  • 1
  • 3
  • 16
  • Could you please try again by replacing `this.httpClient.get(this.apiUrl + "GetCompany_test")` with `this.httpClient.get(this.apiUrl + "GetCompany_test", { "observe": "body" })` and see if it throws any error? – ruth Mar 31 '20 at 11:16
  • No error in the console.The response is still same. – vivek v Mar 31 '20 at 12:16

1 Answers1

1

Casting among another uses is basically for intellisense to help you. When you call this get method and pass it the IEmployee type, what you are basically saying is that, 'Hey intellisense, I am expecting a result of the type IEmployee'. So when you subscribe to the result and then try to access it's properties, it will give you the properties defined in IEmployee. Intellisense or the get method can't determine what is to be returned beforehand. So in case you also don't know, you can pass it the any type, which is like saying, 'I don't know what type result will return', so in that case, you can't get any type checking because the type could be any.

Now let's say, you get the results back and after seeing it, it looks like a type you already have so then you can cast it to that type and then Intellisense can step in because now, it knows the type. So let's say:

service.ts

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

component1:

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
});

//component2:

service.GetAll().subscribe((x:IEmployee) => {
// x has a type here so there is type checking.
// Intellisense can help you out here
});
Alf Moh
  • 7,159
  • 5
  • 41
  • 50