【发布时间】:2020-05-22 10:41:03
【问题描述】:
我可以同时编辑前端和后端
我有一个获取公报的服务。该公报可能存在(有一个公报处于活动状态)也可能不存在(没有公报处于活动状态),因此 API 可能会使用公报的 JSON 对象或空 JSON 对象进行响应。
我是这样处理的:
getCommunique(): Observable<Communique | {}> {
return this.http.get(this.apiUrl + '/getCommunique').map((response) => {
if (Object.keys(response.json()).length != 0) {
return new Communique(response.json())
} else {
return {}
}
});
}
这是我的Communique 班级:
export class Comunique {
public id: number;
public title: string;
public content: string;
public date: Date;
public url: string;
public imageUrl: string;
constructor(input: ComuniqueRaw) {
this.id = input.id;
this.title = input.title;
this.content = input.content;
this.date = new Date(input.date.timestamp * 1000);
this.url = 'url' + input.slug;
this.imageUrl = 'url' + input.image;
}
}
这行得通...但这似乎是一种解决方法。 observable 不应该只返回Communique 对象吗?但是如果没有有效的公报,Communique 对象将如何创建?我的意思是,我可以在Communique 类中添加一个类似于public exists: boolean; 的字段,但这似乎也是一种解决方法(一个只包含一个boolean 的对象)。
我是否以正确的方式处理它?或者...如何使用 rxjs Observables 处理可能是空对象的 API 响应?
【问题讨论】:
标签: angular api ionic-framework rxjs ionic3