组件传数据给服务1,服务2依赖服务1,服务2数据给组件

Pass data from component to service 1. Service 2 depends on service 1. Service 2 data to component

我正在创建天气应用程序。

我有 view.componentcoord.serviceweather.service

我有 view.component 供用户输入。我想将来自组件的输入传递给 coord.service,这会进行 API 调用和 returns 坐标。坐标应该传递给 weather.service,它也会进行 API 调用,returns 一个 Observable 返回给 view.component 以渲染到 HTML。我想不出 out/understand 如何做到这一点。

view.component.ts:

@Component({
  selector: 'app-view',
  templateUrl: './view.component.html',
  styleUrls: ['./view.component.css']
})

export class ViewComponent implements OnChanges {
  alerts: any;
  currData:any = {};

  @Input() location: string;

  coordinate = [];

  constructor(public weatherService: WeatherService) { }

  ngOnChanges(changes: SimpleChanges) {
    // pass location to coord.service -> i don't know what to do from here
    //this.weatherData(this.coordinate);
  }

  weatherData(coord: Array<number>) {
    this.weatherService.getWeatherInfo(coord).subscribe((data) => {
     // do something with data and make it render
    });
  }

coord.service

@Injectable({
  providedIn: 'root'
})
export class CoordinateService {

  readonly coord_API = ""

  constructor(private http : HttpClient) {  }

  getCoordinates(location : string) {
    return this.http.get(this.coord_API.replace("*", location)).pipe(
      tap(_ => console.log("recieved geoData")),
      catchError(err => {throw "GEO ERROR: " + err})
    )
  }
}

weather.service

@Injectable({
  providedIn: 'root'
})
export class WeatherService {
  readonly weather_api : string = "";
  coordinates : [] = [];
  // I need to pass in input from component to coordService
  constructor(public http : HttpClient, public coordinateService : CoordinateService) {  }

  getWeatherInfo(coordinates : Array<number>, type="daily") {
    return this.http.get(this.weather_api).pipe(
      tap(_ => console.log('got data')),
      catchError(err => {throw "WE. ERR : " + err})
    );
  }
}

您的组件应该聚合服务并进行调用。

constructor(
  public weatherService: WeatherService,
  public coordsService: CoordinateService,
) { }

weatherData() {
  this.coordsService.getCoordinates('your param').pipe(
    switchMap(coords => this.weatherService.getWeatherInfo(coords))
  ).subscribe(data => console.log(data));
}

服务是可以注入到 Angular 中的任何内容的提供者。它们应该有一个单一的目的:然后组件应该能够使用它们并将它们组合起来。

switchMap 是一个 RxJS 运算符。

RxJS 是 Angular 广泛使用的一个库,它支持 reactive programming。当您进行 HTTP 调用时,您会创建一个观察者,它是通过 subscribe 关键字创建的。这会创建一个流,其中的数据是不可变的。

RxJS 允许您使用运算符来操作流。您有 a lot of operators 可供选择。

switchMap 的情况下:这是一个允许您将流切换为另一个流的运算符。这意味着您首先请求坐标,然后使用 switchMap 请求天气,以及第一个 http 调用的结果。

你有几个运算符,比如 mergeMapflatMap ... 但是 switchMap 应该始终是第一选择,因为如果可观察对象是,它会取消任何待处理的请求再次被观察。这意味着如果用户连续多次点击该按钮,他将取消挂起的请求,从而减少 http 调用。