繁体   English   中英

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

[英]Angular2 define json observable return type to interface or class model

我希望将我的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[]; 将是一个User对象数组,但事实并非如此。 响应数组的控制台日志

我在这做错了什么?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM