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

Rob*_*rto 4 json interface angular

我希望将我的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
}
Run Code Online (Sandbox Code Playgroud)

以下界面和型号:

Users.ts

import {User} from "../User";
export interface Users{
    count: number,
    users: Array<User>,
}
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

users.component.html

<ul>
    <li *ngFor="let user of users">
        {{ user.username }}
    </li>
</ul>
Run Code Online (Sandbox Code Playgroud)

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

我在这做错了什么?

Ami*_*mit 7

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

你基本上是"强制转换"(或简称"引用")一个简单的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)));
}
Run Code Online (Sandbox Code Playgroud)

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