Angular2将json observable返回类型定义为接口或类模型

时间:2017-03-05 12:00:19

标签: json angular interface

我希望将我的json api响应水合成一个类或基于一个接口,所以我总是知道我有什么属性。 我有以下JSON:

{
  "users": [
    {
      "id": "bd3d70fd-03f7-4f5e-9ac1-4cb7221e352d",
      "username": "caroga",
      "username_canonical": "caroga",
      "email": "caroga@caroga.net",
      "email_canonical": "caroga@caroga.net",
      "groups": [],
      "roles": [],
      "games": [],
      "_links": {
        "self": {
          "href": "/app_dev.php/api/users/bd3d70fd-03f7-4f5e-9ac1-4cb7221e352d"
        },
        "users": {
          "href": "/app_dev.php/api/users/"
        }
      }
    },
    {
      "id": "df33d9cb-b575-427f-b2bd-ed9c364110f7",
      "username": "joemi",
      "username_canonical": "joemi",
      "email": "joemi@joemi.nl",
      "email_canonical": "joemi@joemi.nl",
      "roles": [],
      "games": [],
      "_links": {
        "self": {
          "href": "/app_dev.php/api/users/df33d9cb-b575-427f-b2bd-ed9c364110f7"
        },
        "users": {
          "href": "/app_dev.php/api/users/"
        }
      }
    }
  ],
  "count": 2
}

以下界面和型号:

Users.ts

import {User} from "../User";
export interface Users{
    count: number,
    users: Array<User>,
}

User.ts

export class User {
    id: string;
    username: string;
    username_canonical: string;
    email: string;
    email_canonical: string;
    groups: Array<string>;
    roles: Array<string>;
    games: Array<string>;

    constructor(values: Object = {}) {
        Object.assign(this, values);
    }
}

user-data.service.ts

import {Injectable} from "@angular/core";
import {Http} from "@angular/http";
import {ApiService} from "./api.service";
import {environment} from "../../environments/environment";
import {Observable} from "rxjs";
import {Users} from "../Models/Interfaces/Users";

@Injectable()
export class UserDataService extends ApiService {

    constructor(private http: Http) {
        super();
    }

    getAllPlayers(): Observable<Users> {
        return this.http.get(environment.apiUrl + '/users/', this.addJwtHeader())
            .map(result => result.json());
    }
}

users.component.ts

import {Component, OnInit} from "@angular/core";
import {UserDataService} from "../../services/user-data.service";
import {User} from "../../Models/User";
import {Observable} from "rxjs";
import {Users} from "../../Models/Interfaces/Users";

@Component({
    selector: 'app-users',
    templateUrl: './users.component.html',
    styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {

    private users: User[];

    constructor(private PlayerDataService: UserDataService) {
    }

    ngOnInit(): void {
        this.getListOfAllUsers().subscribe(users => {
            console.log(users);
            this.users = users.users;
        });
    }

    public getListOfAllUsers(): Observable<Users> {
        return this.PlayerDataService.getAllPlayers();
    }
}

users.component.html

<ul>
    <li *ngFor="let user of users">
        {{ user.username }}
    </li>
</ul>

手头的问题: 虽然我在屏幕上获得结果,但它仍然使用json参数而不是模型中定义的参数。 我注意到这一点,因为更改username中的User.ts属性不会引发错误甚至反映在控制台中的对象中。 基本上我预计private users: User[];将是一个User对象数组,但事实并非如此。 Console log of response array

我在这里做错了什么?

1 个答案:

答案 0 :(得分:7)

getAllPlayers(): Observable<Users> {
    return this.http.get(environment.apiUrl + '/users/', this.addJwtHeader())
        .map(result => result.json());
}

你基本上是“施放”(或简称“引用”)一个简单的JS对象(从json()函数返回到期望成为的对象用户,但它无法正常工作。 TypeScript只能帮助你跟踪所有内容,但是当将对象转换为类时,TypeScript只能做很多事情,你不能真正接受一个对象并将其转换为类的实例,这不是OOP的工作方式

我猜你想做的事情可能是这样的:

getAllPlayers(): Observable<Users> {
    return this.http.get(environment.apiUrl + '/users/', this.addJwtHeader())
        .map(result => result.json().map(obj => new User(obj)));
}

(当然感谢你的构造函数)