加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:22:58 所属栏目:安全 来源:网络整理
导读:我希望将我的json api响应水合成一个类或基于一个接口,所以我总是知道我有什么属性. 我有以下 JSON: { "users": [ { "id": "bd3d70fd-03f7-4f5e-9ac1-4cb7221e352d","username": "caroga","username_canonical": "caroga","email": "caroga@caroga.net","em
我希望将我的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","_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);
    }
}

用户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中的用户名属性不会引发错误甚至反映在控制台中的对象中.
基本上我期望私人用户: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)));
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读