Angular 5 + Typescript - 返回新创建的类型对象的数组

时间:2017-12-05 13:38:15

标签: angular typescript

我有一项服务,我从后端检索“时刻”。我有2个功能。一个返回1个对象的get()方法和一个返回一个对象数组的search()方法。

moment.service.ts

在get方法中,我从后端映射res以创建我的Moment类的新实例。哪个工作正常。

   get(moment_id) {

        let endpoint = this.path + moment_id;

        return this.apiService.get(endpoint)
                              .map((res) => new Moment(res.data));
    }

我想在搜索方法中做同样的事情。它应映射数组,以使其中的所有对象都是时刻类的新实例。

search(filters) {

    let endpoint = this.path + 'search';

    let params = new HttpParams({ fromObject: filters });

    return this.apiService.get(endpoint, params)
                          .map((res) => new Array<Moment>(res));
}

但是,这不起作用返回的数组不显示对象是Moment类型。

enter image description here

moment.component.ts

   moments: Moment[] = [];

    this.momentService.search(filters).subscribe((res) => {
                this.moments = res;
                console.log(this.moments);
            });

moment.model.ts

import { Comment } from './comment.model';
import { User } from './user.model';

export class Moment {

    _id?: string = null;
    body?: string = null;
    author?: User = null;
    likes?: any[] = [];
    dislikes?: any[] = [];
    comments?: Comment[] = [];
    created_at?: string = null;
    updated_at?: string = null;


    constructor(data?: Moment) {
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: Moment) {

        const keys = Object.keys(this);
        for (const key of keys) {
            if (key === 'author') {
                this[key] = new User(data['author']);
            } else if (key === 'comments') {
                this[key] = data['comments'].map(c => new Comment(c));
            } else {
                this[key] = data[key];
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

尝试按如下方式实例化时刻:

search(filters) {

    let endpoint = this.path + 'search';

    let params = new HttpParams({ fromObject: filters });

    return this.apiService.get(endpoint, params)
                          .map((res) => new Array<Moment>(new Moment(res)));
}