在 Angular 中将数据从服务传递到模态组件

Passing data from service to modal component in Angular

我是 Angular 编程新手。我试图将数据从服务传递到我的模态组件,但首先显示一个空模态,然后数据出现(我可以在 console.log 中看到数据,或者当我第二次打开模态时)。这是我的代码:

geoname.service.ts

export class GeonameService {

  private geonames: Geoname[] = [];
  private geonamesUpdated = new Subject<Geoname[]>();

  constructor(private http: HttpClient) {}

  getCity(searchText: string, country: string) {
    const queryParams = `?apikey=` + environment.opendataKey + `&dataset=xxxxx&rows=50&sort=place_name&q=` + searchText + `&refine.country_code=` + country;
    this.http
      .get(environment.opendataUrl + queryParams)
      .pipe(
        map(geonameData => {
          return geonameData[`records`].map(data => {
            return {
              country: data.fields.country_code,
              zipcode: data.fields.postal_code,
              place: data.fields.place_name,
              admin: data.fields.admin_name2,
              latitude: data.fields.latitude,
              longitude: data.fields.longitude
            };
          });
        })
      )
      .subscribe(transformedGeonameData => {
        this.geonames = transformedGeonameData;
        this.geonamesUpdated.next([...this.geonames]);
      });
  }

  getGeocodeListener() {
    return this.geonamesUpdated.asObservable();
  }

}

地图-view.component.ts

export class MapViewComponent implements OnInit {

  @ViewChild('searchCityInput', { static: false }) searchCityInput: ElementRef;
  @ViewChild('countrySelect', { static: false }) countrySelect: ElementRef;

  private geonames: Geoname[] = [];

  constructor(private basicService: BasicService, private geonameService: GeonameService, private modalService: ModalService) {}

  ngOnInit() {
    this.geonameService.getGeocodeListener().subscribe(data => {
      this.geonames = data;
    });
  }

  searchCity() {
    this.geonameService.getCity(this.searchCityInput.nativeElement.value, this.countrySelect.nativeElement.value);
    this.modalService.showGeonameModal(this.geonames);
  }

}

我知道这是异步的,代码不是依次执行的。除此之外,如果我编程正确,请检查我的其余代码。

尽量避免在您的服务中订阅,而只是从您的组件订阅。这将允许您重用此代码并让您的组件更好地控制请求完成后发生的事情。

getCity(searchText: string, country: string) {
    const queryParams = `?apikey=` + environment.opendataKey + `&dataset=xxxxx&rows=50&sort=place_name&q=` + searchText + `&refine.country_code=` + country;
    return this.http.get(environment.opendataUrl + queryParams).pipe(
        map(geonameData => {
            return geonameData[`records`].map(data => {
                return {
                    country: data.fields.country_code,
                    zipcode: data.fields.postal_code,
                    place: data.fields.place_name,
                    admin: data.fields.admin_name2,
                    latitude: data.fields.latitude,
                    longitude: data.fields.longitude
                };
            });
        })
    );
}

然后你所要做的就是在请求完成后打开模式:

searchCity() {
    this.geonameService.getCity(this.searchCityInput.nativeElement.value, this.countrySelect.nativeElement.value).subscribe((geoNames) => {
        this.modalService.showGeonameModal(geoNames);
    });
}

除非您在其他订阅者之间共享此数据,否则您可能根本不需要使用 Subject()。