如何从firestore获取数据并在其中获取另一个数据(通过引用)

时间:2018-01-31 23:34:58

标签: javascript firebase google-cloud-firestore angularfire5

当我在数据模型引用(id)中有另一个对象时,我无法弄清楚如何从firestore获取数据,例如像这样

City {name:      string;
       countryId: string; //primary key to another object in database
}
Country {
      name: string;
}

我正在使用AngularFire 5.

在我获取城市后,我想要获取国家/地区,我想将country.name asign到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() {}
    }

1 个答案:

答案 0 :(得分:2)

所以我设法最终解决了这个问题。 这是来自servis的代码。

 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中使用引用和地理类型。

相关问题