转换响应(例如json数据)到角度模型的好习惯是什么?因此,换句话说,如何在角度2中实现自动映射器功能。
team.service.ts
pip install sk-video
team.data.json
import skvideo.io
cap = skvideo.io.vreader(input_video_filepath)
metadata = skvideo.io.ffprobe(input_video_filepath)
framerate = metadata['video']['@r_frame_rate']
for frame in cap:
# Do whatever you want...
# "cap" is a generator, the for loop will simply end when there are no more frames
# "frame" is a NumPy array, just like in OpenCV's VideoCapture
team.model.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Team } from './team.model';
@Injectable()
export class TeamService {
constructor(private _http: Http) {
}
public GetAllTeams(): Promise<Team[]> {
return this._http.get('/app/teams/shared/team.data.json')
.toPromise()
.then(respons => <Team[]> respons.json().data as Team[])
.then(data => { return data; });
}
}
方法{
"data": [
{"id": "1", "name": "Team 1", "otherProperty" : "S1"},
{"id": "2", "name": "Team 2", "otherProperty" : "S2"},
]
}
应返回export class Team {
private _id: string;
public get id(): string {
return this._id;
}
public set id(value: string) {
this._id = value;
}
private _name: string;
public get name(): string {
return this._name;
}
public set name(value: string) {
this._name = value;
}
private _icon: string;
public get icon(): string {
return this._icon;
}
public set icon(value: string) {
this._icon = value;
}
}
个对象。我知道我可以创建接收json数据的工厂并返回Team对象的数组,但是在阅读了这篇文章https://angular.io/docs/ts/latest/guide/dependency-injection.html(car-factory.ts部分)之后,它似乎是糟糕的模式。
感谢。
答案 0 :(得分:4)
实际上,如果您需要的是强类型,则无需创建类作为模型。您可以改用Interface。
export interface Team {
id: string;
name: string;
icon: stirng;
someOtherProperty: [];
}
使用Interface的好处是你可以获得强大的输入,而没有为接口生成代码,而类会生成额外的代码。
现在我认为你做出回应转换的方式很好,恕我直言。
public GetAllTeams(): Promise<Team[]> {
return this._http.get('/app/teams/shared/team.data.json')
.toPromise()
.then(respons => respons.json())
.then(x => x.data);
}
永远记住TypeScript是Javascript +强类型。不要试图引入所有OO实现(虽然它有时很诱人)。