等待异步数据后将 AngularFire 数据绑定到 属性

Bind AngularFire data to a property after waiting for async data

我想 get 使用包含 lat/lng 坐标的 URL 参数使用 AngularFire 从 Firestore 获取特定文档,然后将这些坐标绑定到 google-map 组件的[center] 属性 根据查看的项目动态显示地图。但是数据没有连接到 google 地图 属性,所以它默认以 Google 总部位置为中心。

主组件 List 在我提取的 URL hike/:hikeId 中为事件传递一个 id,然后使用 AngularFire 获取文档。

加息-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>

加息-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 HQ 为中心的 google 地图,也就是 [center] 绑定不起作用。

里面ngOnInit()订阅observable并获取值:

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>