我正在尝试使用新的HttpClientModule
填充API调用的响应模型。但是,模型的属性不是“json类型”,而是复杂类型。
您是否知道我的getById
和getAll
ReferenceService
方法如何返回与真实Observable
对象匹配的Reference
而不仅仅是json对象?
以下是我想做的一个例子。
谢谢!
class Reference {
id: number;
title : string;
type : Type;
date : Date;
tags : Array<Tag>;
constructor(id : number = null, title : string = '', type : Type = new Type(), date : Date = new Date(), tags : Array<Tag> = []) {}
display() {
console.log(this.title);
this.type.display();
}
}
class Type {
id: number;
name : string;
constructor(id : number = null, name : string = '') {}
display() { console.log(this.name); }
}
class Tag {
id: number;
name : string;
constructor(id : number = null, name : string = '') {}
}
@Injectable()
class ReferenceService {
constructor(private http : HttpClient) {}
getById(id: number) {
return this.http.get<Reference>('/api/reference/'+id);
}
getAll() {
return this.http.get<Array<Reference>>('/api/references');
}
}
@Component({
providers: [ReferenceService]
})
class ReferenceComponent implements OnInit {
model: Reference;
constructor(private referenceService : ReferenceService) {}
ngOnInit() {
this.referenceService
.getById(42) // hard coded for testing
.subscribe( (data : Reference) => {
this.model = data;
console.log(this.model.display());
});
}
}
`