Angular 4:使用json HttpClient响应填充复杂模型

时间:2017-11-10 11:26:55

标签: json angular angular-httpclient angular-observable

我正在尝试使用新的HttpClientModule填充API调用的响应模型。但是,模型的属性不是“json类型”,而是复杂类型。

您是否知道我的getByIdgetAll 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());
            });
    }
}

`

0 个答案:

没有答案