作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
当我在数据模型中引用 (id) 到另一个对象时,我不知道如何从 firestore 获取数据,例如这样
City {name: string;
countryId: string; //primary key to another object in database
}
Country {
name: string;
}
我正在使用 AngularFire 5。
获取城市后,我想获取国家,我想将 country.name 分配给 city.countryId,我想返回加入的对象城市。
我为此提供了服务,因为我想从代码中的多个位置获取这些数据。
@Injectable()
export class CityService implements OnInit {
city: City;
constructor(
private dataFetch: FireStoreService) { }
ngOnInit() {}
getCity(ref: string): City {
this.dataFetch.getDataDoc(ref).subscribe((_city: City) => {
this.dataFetch.getDataDoc(_city.countryId)
.subscribe((country: Country) => {
_city.countryId = country.name;
this.city = _city;
});
});
return this.city;
}
}
是的,我知道这是行不通的,因为它是异步任务,我已经阅读了很多文章,但我还是想不通。所以我不知道如何获取一些对象,然后从该对象获取引用并返回连接对象(没有引用但有正确的数据)。
这是我的城市组成部分。
@Component({
selector: 'app-detail-city',
template: `
<p> detail-city works! </p>
<p> Name : {{ city.name }} </p>
<p> Country : {{ city.countryId }} </p>
<p> ID : {{ city.id }} </p>
`,
styleUrls: ['./detail-city.component.css']
})
export class DetailCityComponent implements OnInit {
city: City;
root: string;
constructor(
private route: ActivatedRoute,
private cityService: CityService) {
this.route.params.subscribe(
(params: Params) => {
this.root = params['root']+'/'+params['id'];
this.city = cityService.getCity(this.root);
});
}
ngOnInit() {}
}
最佳答案
所以我最终设法解决了这个问题。这是来自服务的代码。
getCity(ref: string): Observable<City> {
return this.dataFetch.getDocument(ref)
.switchMap((res: City) => {
return this.dataFetch.getDocument(res.countryId)
.map((country: Country) => {
return new City(
res.id,
res.name,
country.name
);
});
});
}
然后你可以在你的组件中订阅这个 observable 或使用异步管道。另外,我发现有用 link其中描述了如何在 FireStore 中使用引用和地理类型。
关于javascript - 如何从 firestore 获取数据并在其中获取另一个数据(通过引用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48553195/
我是一名优秀的程序员,十分优秀!