Something peculiar caught my attention in my Angular2 TypeScript project. When objects are fetched from a web service, they have the type "Level" and the properties are in Pascal case. However, during runtime, I noticed that the properties of these Levels have lowercase letters in my TypeScript project (as seen in the browser's developer debug tool).
I believe I need to somehow map the JSON properties instead of using "as Level[]" for casting everywhere. How can I achieve this properly?
Update: In response to requests for code samples:
(Controller)
ngOnInit(): void {
this.levelsObservable = this.levelsService.getAllLevels();
this.levelsObservable.subscribe(
data => console.log(data)
);
}
(Service)
observable : Observable<Response>;
getAllLevels(): Observable<Level[]> {
this.observable = this.achievementsService.getAllAchievements(this.allLevelsUrlPart);
return this.observable
.map((response: Response) => {
const srcData = response.json() as Level[];
return srcData;})
.catch(error => this.handleError(error));}
getAllAchievements(detailPath): Observable<Response> {
// prepare request url and header
this.specificUrl = this.webServiceUrl + detailPath;
this.headers.append('Content-type', 'application/json');
let options = new RequestOptions({ headers: this.headers });
this.result = this.http.get(this.specificUrl, options)
.catch(error => this.handleError(error));
return this.result;}
Update: I made some improvements to my code with help from a previous answer (not included above as it does not address the main issue). I attempted to implement another suggestion to convert to camel case but encountered difficulties accessing object properties within an array.
Update: Success! After hours of searching, I finally found a solution (!). I've condensed this post and will share my solution below. It may not be perfect, but I'm grateful for all the helpful advice provided here!