javascript - 等待异步数据后将 AngularFire 数据绑定(bind)到属性

标签 javascript angular firebase google-cloud-firestore angularfire

我想使用 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/

相关文章:

javascript - 6 个网格 DIV,每个带有 2 个内容 DIV 和切换功能

javascript - Angular 2 - API 请求未返回 Observable,错误 : undefined has no property 'length'

angular - 在 Angular(4) 中使用拆分应用程序模块进行导入(客户端、服务器、共享)

android - 无法解析 FirebaseMessagingService android

ios - 使用 Firebase 检索的数据设置变量

android - 来自 Firebase 的数据未显示在 RecyclerView 上

javascript - iOS Safari 是否支持 storageEvents?

angular - ionic : undefined is not a constructor FileReader

Angular 7 PATCH方法将元素添加到列表

javascript - 如何监控用户在线状态(实时)