I want to convert a angular2 observable to a class
Asked Answered
G

2

8

I am new in angular2 and I broke spend a lot of time to find a solution, but I didn't. I want to convert a oberservable from a http call store in a class.

I have the following:

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 which read the a 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");
  }

And the componenten which take the oberservable and store it to the a 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);
      }
....

As I run this I getting 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 hope anyone out there can help me on that. I just want to parse of a json file into a class that i can read the properties like this "User.name"

Goldplate answered 12/2, 2017 at 16:16 Comment(0)
T
5
 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 ));
          });
        }
        return result; // <<<=== missing return
      })
      .subscribe(user => this.user = user);
  }
Tweezers answered 12/2, 2017 at 16:18 Comment(3)
Thanks a lot! This help! Just one more question. I thought I can now use the user on the template by using e.g {{user.name}} but it doesn't work. I am confused!? Sorry, I am new in typescript.Goldplate
I guess you just need {{user?.name}} to avoid errors while that user is still null (until the data arrives from the server).Blenny
Thanks once again, it is correct if I am using {{user?.name}} it worked :-) Which I was suprised because I am reading a local file, also I thougt ngOnInit is before redering .....hmmm okay thank you for you fast help...Goldplate
R
-1

You dont need to manually parse json to Object. You do something like below -

 getUser(): Observable<User[]> {
    return this.http.get(this.useUrl)
      .map(data => <User[]>data);
  }
Ramos answered 12/2, 2017 at 16:26 Comment(3)
That doesn't work if the class has methods or getters/setters though, the resulting instance won't have these.Blenny
@GünterZöchbauer I think I was able to cast json to typescript object with getters/setters before. I will check it.Ramos
No, casting is only to satisfy the static code analysis, but at runtime this has no effect at all, the value stays plain JSON.Blenny

© 2022 - 2024 — McMap. All rights reserved.