Take a look at this snippet from my AngularJS 2 application:
DataItem
export class DataItem {
id: number;
name: string;
}
DataService
[...]
export class DataService {
constructor(private http: Http) {}
fetchData(): Observable<DataItem> {
return this.http
.get("http://www.example.com")
.map(this.save)
.catch(this.fail);
}
private save(response: Response) {
let dataItem: DataItem = <DataItem> response.json();
return dataItem || {};
}
private fail(error: any) {
return Observable.throw("error!");
}
}
MainComponent
[...]
export class MainComponent implements OnInit {
dataItem: DataItem;
constructor(private dataService: DataService) {}
ngOnInit() {
this.dataService.fetchData().subscribe(
result => {
this.dataItem = new DataItem();
console.log(this.dataItem); // prints (empty) DataItem
this.dataItem = result;
console.log(this.dataItem); // prints object, not DataItem?
},
error => { }
);
}
}
Now, I have some questions:
1) Why is the type object
printed in Chrome Inspector instead of DataItem
?
2) The property dataItem
in the MainComponent
class should be of type DataItem
. Why isn't there an error?
3) How can I ensure that I actually receive DataItem
? What is the best way to achieve this? Is there a way to automatically map the JSON response to my object?