【问题标题】:How to use behavioursubject to change parameters in service function如何使用 behaviorsubject 更改服务功能中的参数
【发布时间】:2022-12-17 15:05:48
【问题描述】:

您好,我正在尝试根据在主组件中单击哪个按钮来实现数据表组件中更改数据的行为,但无法弄清楚它确实令人困惑。

所以我有服务功能,它使用两个参数从 api 获取数据,并单击主组件中的按钮我想更改服务的参数,以便数据表组件信息使用新参数更新 这是服务

export class WeatherService {
  constructor(private http: HttpClient) {}

  getWeatherData(
    lat: string = '51.51',     //these are default parameters for london
    lon: string = '-0.13'   //i want to change these with click from home component 
  ): Observable<WeatherData> {
    return this.http.get<WeatherData>(
      `https://archive-api.open-meteo.com/v1/era5?latitude=${lat}&longitude=${lon}&start_date=2005-08-25&end_date=2005-08-25&hourly=temperature_2m,relativehumidity_2m,dewpoint_2m,apparent_temperature,surface_pressure,precipitation,rain,cloudcover,windspeed_10m,winddirection_10m,soil_temperature_0_to_7cm`
    );
  }
}

该服务在这里使用默认服务参数,但想根据在主页上单击的城市按钮更改参数

ngOnInit(): void {
    this.weatherDataLoading = true;
    this.weatherService      
      .getWeatherData()     //service is used here with default parameters (lat,long for london)
      .pipe(
        finalize(() => (this.weatherDataLoading = false)),
        takeUntil(this.componentDestroyed$)
      )
      .subscribe({
        next: (historicalWeatherData) => { ...code

这是带有按钮的主页组件和到天气数据组件的每个路由,每个组件都应在单击时将新参数(纬度、经度)传递给服务

<div class="container">
  <div class="grid">
    <button pButton type="button" routerLink="/weather-data">London</button>
    <button pButton type="button" routerLink="/weather-data">New York</button>
    <button pButton type="button" routerLink="/weather-data">Tokyo</button>
    <button pButton type="button" routerLink="/weather-data">Sydney</button>
    <button pButton type="button" routerLink="/weather-data">Madrid</button>
    <button pButton type="button" routerLink="/weather-data">Paris</button>
  </div>

例如,当我在主页按钮中单击东京时,它会将我重定向到天气数据表组件并更改服务中的纬度和经度,以便显示东京的准确数据,而不是伦敦的默认纬度和经度参数

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    您只需要一个可重用的功能(在您的组件或服务中)负责:

    • 通过 weatherService.getWeatherData 方法调用 GET 端点,必要时使用坐标
    • 应用操作符(例如 finalize)

    该解决方案不使用 BehaviorSubject,但我相信可以达到预期的结果。如果 BehaviorSubject 出于某种原因是强制性的,我可以包含一个额外的答案

    service.ts

      getWeatherData$(
        lat: string = '51.51',     //these are default parameters for london
        lon: string = '-0.13'   //i want to change these with click from home component 
      ): Observable<WeatherData> {
        return this.http.get<WeatherData>(
          `https://archive-api.open-meteo.com/v1/era5?latitude=${lat}&longitude=${lon}&start_date=2005-08-25&end_date=2005-08-25&hourly=temperature_2m,relativehumidity_2m,dewpoint_2m,apparent_temperature,surface_pressure,precipitation,rain,cloudcover,windspeed_10m,winddirection_10m,soil_temperature_0_to_7cm`
        );
      }
    

    component.ts

    ngOnInit(): void {
      this.getWeatherData();
    }
    
    getWeatherData(coordinates?: { lat: number, long: number }): void {
      const weatherData$: Observable<WeatherData> =
        coordinates
          ? this.weatherService.getWeatherData$(coordinates.lat, coordinates.long)
          : this.weatherService.getWeatherData$();
    
      const weatherDataWithLoader$: Observable<WeatherData> =
        defer(
          () => {
            this.weatherDataLoading = true;
    
            return weatherData$
              .pipe(
                finalize(() => { this.weatherDataLoading = false }),
                takeUntil(this.componentDestroyed$)
              )
            }
        )
    
      weatherDataWithLoader$
        .subscribe({
            next: (historicalWeatherData: WeatherData) => { // ...code }
        })
    }
    

    component.html

    <div class="container">
      <div class="grid">
        <button pButton type="button" routerLink="/weather-data" (click)="getWeatherData({lat: 123, lon: 123}")>London</button>
        <button pButton type="button" routerLink="/weather-data" (click)="getWeatherData({lat: 456, lon: 456}">New York</button>
        ...
      </div>
    </div>
    

    根据您的用例和您对数据的处理方式,这可以进一步改进

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-20
      • 1970-01-01
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      • 1970-01-01
      相关资源
      最近更新 更多