如何重用 CRUD 方法中的可观察值

Posted

技术标签:

【中文标题】如何重用 CRUD 方法中的可观察值【英文标题】:How to reuse the observable values in CRUD methods 【发布时间】:2022-01-23 09:13:21 【问题描述】:

在我的get resquest中,我需要发送headerParams的集合,而不是调用方法来获取headerParams如何调用和存储为静态值?

如何确保其他方法等到标题详细信息可用?我正在做最坏的做法。有人帮帮我吗?

这是我的服务 ts 文件:

    export class ForecastService extends EntityCollectionServiceBase<OpenWeatherResponse> implements OnInit 
    
      private url = 'https://api.openweathermap.org/data/2.5/forecast';
      httpUrlGenerator: any;
      headersParams: any; //always underfed
    
      constructor(serviceElementsFactory: EntityCollectionServiceElementsFactory, private http: HttpClient, private notificationService: NotificationsService) 
        super('Forecast', serviceElementsFactory);
      
    
      ngOnInit() 
        this.headersParams = this.getCurrentLocation().subscribe(header => 
          this.headersParams = header; //not working. undefined
        );
      
    
      override getAll(): Observable<OpenWeatherResponse[]> 
    
    //need to avoid it
        return this.getCurrentLocation().pipe(
          map(coords => 
            return new HttpParams()
              .set('lat', String(coords.latitude))
              .set('lon', String(coords.longitude))
              .set('units', 'metrics')
              .set('appid', '21ef99128f486ce0cb0f0612b7c2d567')
          ),
          switchMap(params => this.http.get<OpenWeatherResponse[]>(this.url, params)),
          map((value: any) => value.list),
          mergeMap((value: OpenWeatherResponse[]) => of([...value])),
          filter((value, index) => index % 8 === 0),
          map(value => value)
        )
      
    
      getForecast() 
//need to avoid it
        return this.getCurrentLocation()
          .pipe(
            map(coords => 
              return new HttpParams()
                .set('lat', String(coords.latitude))
                .set('lon', String(coords.longitude))
                .set('units', 'metrics')
                .set('appid', '21ef99128f486ce0cb0f0612b7c2d567')
            ),
            switchMap(params => this.http.get<OpenWeatherResponse>(this.url, params)),
            pluck('list'),
            mergeMap(value => of(...value)),
            filter((value, index) => index % 8 === 0),
            map(value => 
              return 
                dateString: value.dt_txt,
                temp: value.main.temp
              
            ),
            toArray(),
            share()
          )
      
    
      getCurrentLocation() 
//looking to call as a first method and need to save in variable
        return new Observable<GeolocationCoordinates>(observer => 
          window.navigator.geolocation.getCurrentPosition(
            position => 
              observer.next(position.coords);
              observer.complete();
            ,
            err => observer.error(err)
          )
        ).pipe(
          retry(1),
          tap(
            next: () => this.notificationService.addSuccess('Got your location'),
            error: catchError((err) => 
              this.notificationService.addError('Failed to get the location');
              return throwError(() => new Error(err));
            )
          ))
      
    
    

请检查我的 cmets 以了解我的要求。

【问题讨论】:

【参考方案1】:

您可以创建一个共享的 observable 并使用 shareReplay 添加缓存,以避免每次调用 api

headers$ = this.getCurrentLocation().pipe(
   map(coords => 
          return new HttpParams()
            .set('lat', String(coords.latitude))
            .set('lon', String(coords.longitude))
            .set('units', 'metrics')
            .set('appid', '21ef99128f486ce0cb0f0612b7c2d567')
   ),
   shareReplay(1) // caching
)

然后以这种方式使用它

getForecast() 
   this.headers$.pipe(
     switchMap(params => this.http.get<OpenWeatherResponse>(this.url, params)),
     pluck('list'),
     ...
   )

【讨论】:

以上是关于如何重用 CRUD 方法中的可观察值的主要内容,如果未能解决你的问题,请参考以下文章

如何在运行时调用存储在HP ALM-QC中的可重用操作

如何将用户输入转换为 gnu prolog 中的可重用谓词?

如何创建复制现有指令的可重用 AngularJs 指令

如何停止 UIPickerView 的可重用性

Magnolia 中的可重用表单组件

React 中的可重用文本字段