是否有任何选项可以从一个订阅中获取两个值?第一个是所有配置文件数据,第二个是按名称过滤的最喜欢的数据。我想尽可能少地使用firebase请求。
数据库结构:
profile{
uid{
name,
age,
favorite{
name,
uid,
}
}
}
这个组件代码:
ngOnInit() {
this.db.getDataObj("/Profile/" + this.uid).subscribe(res =>{
console.log("Profile Result");
console.log(res);
});
this.db.getDataObj("/Profile/" + this.uid/favorite).subscribe(res =>{
console.log("Profile Result");
console.log(res);
});
这个服务代码:
getDataObj(objpath:string){
this.objRef = this.db.object(objpath);
this.obj = this.objRef.valueChanges();
return this.obj;
}
这是不可能的。一个请求将始终返回一个响应。
但是,查看数据库结构时,您只需要一个请求。
this.db.getDataObj("/Profile/" + this.uid).subscribe(res =>{
console.log("Profile Result");
console.log(res);
});
这里的“res”应该包含完整的配置文件对象(包括“最喜欢的”对象)。
如果你仍然想让这段代码更短/更清洁,你可以考虑创建一个“zip”可观察对象。更多信息here。
如果我的理解是正确的,请创建以下界面:
interface Profile{
uid:uid;
}
interface uid{
name:string;
age:number;
favourite:favourite;
}
interface favourite{
name:string;
uid:string;
}
然后在您的服务中使用以下内容:
getDataObj(objpath:string):Observable<Profile>{
return this.http.get<Profile>(objpath);
}
然后读取喜欢的值,如:
this.db.getDataObj("/Profile/" + this.uid).subscribe(res<Profile> =>{
console.log("Profile Result");
console.log(res.uid.favourite);
});
如果可能的话,尝试使用该uid的配置文件获取与uid收藏夹相关的数据,这样您只需要一次服务调用即可获取所有数据。如果这个电话不是数据重,我认为这是要走的路。否则,如果您将在Profile Service http调用中收到的数据量增加,则查看长期视角,然后使用单独的http调用来获取一个uid的配置文件和收藏夹数据。
这是我第一次在这个论坛回答问题,所以请随时向我提供我的答案的反馈。