Search code examples
javascriptfirebasegoogle-cloud-firestoreangularfire5

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


I can't figure out how to fetch data from firestore when i have in data model reference (id) to another object, for example like this

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

I m using AngularFire 5.

After i fetch city i want fetch country and i want to asign country.name to city.countryId and i want return joined object city.
I made service for this because i want fetch this data from multiple places in code.

@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;
  }
}

Ye i know this will not work beacause it is async task, i have read a lot of articles, but i can not still figure out. So I don't know how to fetch some object and then fetch references from this object and return joined object (without references but with proper data).
This is my city component.

 @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() {}
    }

Solution

  • So i manage to solve this problem at the end. Here is code from 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
                );
              });
          });
      }
    

    Then you can subscribe to this observable in your component or use async pipe. Also, I found usefull link where is described how to use reference and geo type in FireStore.