json - Angular2 将 json observable 返回类型定义为接口(interface)或类模型

标签 json angular interface

我希望将我的 json api 响应整合到一个类中或基于一个接口(interface),这样我就始终知道我拥有哪些属性。 我有以下 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
}

以及以下接口(interface)和模型:

用户.ts

import {User} from "../User";
export interface Users{
    count: number,
    users: Array<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 参数而不是模型中定义的参数。 我注意到这是因为更改 User.ts 中的 username 属性不会引发错误,甚至不会反射(reflect)在控制台中的对象中。 基本上我希望 private users: User[]; 将是一组 User 对象,但事实并非如此。 Console log of response array

我在这里做错了什么?

最佳答案

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

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

关于json - Angular2 将 json observable 返回类型定义为接口(interface)或类模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42608115/

相关文章:

json - 最好使用 Circe 和 Akka Streams 进行流式 JSON 解码

json - Postgres 加入 JSON 列表

json - SQL Server 只读取有效 JSON 的第一行

Angular Lazy Loading(该模块尚未导入到您的模块中)

node.js - angular - node.js,HttpClient 连接成功但没有成功

angular - 更改 Angular2 中的按钮颜色、图标和文本

Android:使用 Moshi 适配器解析内部非结构化 Json

pointers - 接口(interface)不能调用self方法

java - 无界Java通用接口(interface)的问题

android - 接口(interface)没有得到回调Android