簡體   English   中英

如何從Firestore中獲取數據以及如何在其中存儲其他數據(通過引用)

[英]How to fetch data from firestore and inside it fetch another data (by reference)

當我在數據模型引用(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() {}
    }

因此,我最終解決了這個問題。 這是來自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
            );
          });
      });
  }

然后,您可以在組件中訂閱此可觀察項,也可以使用異步管道。 此外,我發現了有用的鏈接 ,其中描述了如何在FireStore中使用參考和地理類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM