【问题标题】:Angular2 define json observable return type to interface or class modelAngular2 将 json 可观察返回类型定义为接口或类模型
【发布时间】:2017-03-05 12:00:18
【问题描述】:

我希望将我的 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 参数而不是模型中定义的参数。 我注意到这是因为更改User.ts 中的username 属性不会引发错误,甚至不会反映在控制台中的对象中。 基本上我预计private users: User[]; 将是一个用户对象数组,但事实并非如此。

我在这里做错了什么?

【问题讨论】:

  • 您对 javascript 有什么期望?不是你的代码转译后使用的吗?
  • 我预计在来自users.component.tsUsers attr 上会有一个包含User.ts 对象的数组。但事实并非如此。
  • 射击,这看起来确实是个问题。我将如何正确地转换这个,for循环并为每条记录实例化模型?
  • 真的是另一个问题,你没有提到你需要实现一个转换引擎。
  • 没有明确说转换引擎,但是我问了如何基于json来水合我的模型,正是这样。创建另一个问题只是这个问题的重复。我还在问题的最后一段The issue at hand 部分解决了这个问题。你能不能再解决一下这个问题?

标签: json angular interface


【解决方案1】:
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)));
}

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

【讨论】:

  • 编辑了另一个错误
猜你喜欢
  • 2018-12-30
  • 2021-03-04
  • 1970-01-01
  • 2011-02-10
  • 2020-11-02
  • 2022-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多