Having recently delved into the world of angular2, I've spent countless hours trying to tackle a particular challenge without success. My goal is to convert an observable from an HTTP call and store it in a class.
Below are the key components involved:
The JSON file:
[{
"nickname": "magicMike",
"id": "123",
"name": "Michael",
"nachname": "Fischer",
"pictURL": "../images/mainPanel/Image_dummy.jpg",
"city": "Ulm"
}]
The user class file:
export class User {
nickname: string;
id: string;
name: string;
nachname: string;
pictURL: string;
city: string;
constructor(
nickname: string,
id: string,
name: string,
nachname: string,
pictURL: string,
city: string
){
this.nickname = nickname;
this.id = id;
this.name = name;
this.nachname = nachname;
this.pictURL = pictURL;
this.city = city;
}
}
The service responsible for reading the JSON file:
import { Component, Input } from '@angular/core';
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { User } from './user'
@Injectable()
export class UserService {
user: Array<User>;
private useUrl = '/json/user.json';
constructor(private http: Http) {
}
getUser(): Observable<any> {
return this.http.get(this.useUrl)
.map(this.extractData)
.do(data => console.log("User from json: " + JSON.stringify(data)))
.catch(this.handleError);
}
private extractData(response: Response) {
let body = response.json();
return body || {};
}
private handleError(error: Response) {
console.log(error);
return Observable.throw(error.json().error || "500 internal server error");
}
The component that receives the observable and stores it in an array:
.......
export class AppComponent implements OnInit {
public user: User[];
ngOnInit() {
this.userService.getUser()
.map((user: Array<any>) => {
let result:Array<User> = [];
if (user) {
user.forEach((erg) => {
result.push(new User(erg.nickname, erg.id, erg.name, erg.nachname, erg.pictURL, erg.city ));
});
}
})
.subscribe(user => this.user = user);
}
....
However, upon running this code, I encounter the following error:
C:/Users/Lenovo/Documents/ui-challenger.one/src/app/app.component.ts (53,26): Type 'void' is not assignable to type 'User[]'.)
I'm reaching out in hopes that someone can offer assistance. All I aim to achieve is parsing a JSON file into a class so that I can access properties like "User.name".