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

心已入冬 提交于 2021-01-28 18:06:47

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/48553195/how-to-fetch-data-from-firestore-and-inside-it-fetch-another-data-by-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!