我想将angular2 observable转换为类

时间:2017-02-12 16:16:43

标签: angular typescript angular-http

我是angular2的新手,我花了很多时间找到解决方案,但我没有。我想从一个类中的http调用存储转换一个oberservable。

我有以下内容:

json文件

[{
    "nickname": "magicMike",
    "id": "123",
    "name": "Michael",
    "nachname": "Fischer",
    "pictURL": "../images/mainPanel/Image_dummy.jpg",
    "city": "Ulm"
}]

用户类文件:

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

读取json文件的服务

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

使用oberservable并将其存储到数组中的组件

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

当我运行这个时,我收到以下错误。

C:/Users/Lenovo/Documents/ui-challenger.one/src/app/app.component.ts (53,26): Type 'void' is not assignable to type 'User[]'.)

我希望那里的任何人都可以帮助我。我只是想将一个json文件解析成一个类,我可以读取这样的属性&#34; User.name&#34;

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

您不需要手动将json解析为Object。你做了类似下面的事情 -

 getUser(): Observable<User[]> {
    return this.http.get(this.useUrl)
      .map(data => <User[]>data);
  }