我想使用 AngularFire 使用包含 lat/lng 坐标的 URL 参数从 Firestore 中获取
特定文档,然后将这些坐标绑定(bind)到 google-map 组件的 [center] 属性以动态显示 map 取决于查看的项目。但数据未连接到 Google map 属性,因此默认以 Google 总部位置为中心。
主组件 List
在 URL hike/:hikeId
中传递一个事件的 ID,我提取该 ID,然后使用 AngularFire 获取文档。
hike-detail.component.html
<h1>Hike Detail</h1>
<h3>Name: <span>{{ (hikeInfo | async)?.name }}</span></h3> // Displays Hike A
<google-map
[center]="hikeInfo.center | async"
width="100%">
</google-map>
hike-detail.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
import { stringify } from 'querystring';
import { map } from 'rxjs/operators';
@Component({
selector: 'app-hike-detail',
templateUrl: './hike-detail.component.html',
styleUrls: ['./hike-detail.component.css']
})
export class HikeDetailComponent implements OnInit {
hikeId;
hikeInfo;
center: google.maps.LatLngLiteral;
constructor(
private route: ActivatedRoute,
private location: Location,
private router: Router,
private firestore: AngularFirestore
) { }
ngOnInit(): void {
this.hikeId = this.route.snapshot.paramMap.get('id');
this.hikeInfo = this.firestore.collection('hikes').doc(this.hikeId).valueChanges();
}
}
数据库
firestore
-- hikes
-- key
-- name: Hike A
-- center: {
lat: 28.12,
lng: 32.71
}
它目前显示名称和以通用 Google 总部为中心的 Google map ,即 [center] 绑定(bind)不起作用。
最佳答案
在ngOnInit()
内部订阅可观察对象并获取值:
this.hikeInfo = this.firestore.collection('hikes').doc(this.hikeId).valueChanges();
this.hikeInfo.subscribe(items => {
console.log(items);
this.center = items.center;
});
然后你可以在html中执行:
<google-map
[center]="center"
width="100%">
</google-map>
关于javascript - 等待异步数据后将 AngularFire 数据绑定(bind)到属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61437510/