首页 > 解决方案 > 如何在离子事件中调用链订阅(RxJs)

问题描述

我有一个 BaseDataService 类,它有一个用于 HttpGet 请求的方法。

protected Get<TResponse>(
    endPoint: string
  ): Observable<BaseResponse<TResponse>> {
    return this.httpClient.get<TResponse>(this.baseUrl + endPoint).pipe(
      map(data => {
        const response = <BaseResponse<TResponse>>{};
        response.Data = data;
        response.Errors = [];
        response.HasError = false;
        return response;
      }),
      catchError(errors => {
        const response = <BaseResponse<TResponse>>{};
        response.Errors = [];
        response.Errors.push(errors.error);
        response.HasError = true;
        return of(response);
      })
    );
  }

我有一个扩展 BaseDataService 的 LocationDeviceDataService,它有一个 Get LocationDevices 的方法

 getAll() {
    return this.Get<BasePaginatedResponse<LocationDeviceResponse>>(
      EndPoints.GET_LOCATIONDEVICES
    );
  }

我在事件中调用这个方法,

this.events.subscribe("connection-type:wifi", () => {
        this.locationDataService.getAll().subscribe(t => {
          localStorage.setItem('LOCATION_DEVICES', JSON.stringify(t.Data.items))
        });
      });

第一次调用时一切都很好,但是当另一个事件(https://ionicframework.com/docs/api/util/Events/)为“connection-type:wifi”发布时, this.locationDataService.getAll().subscribe 返回响应 1x ,2x,4x 等较慢。

我确信后端没有错。

应该取消订阅还是完成订阅?如果我应该,我没有任何触发器。

你能告诉我这段代码有什么问题吗?

标签: rxjsobservablesubscribeionic4ionic-events

解决方案


我解决了我的问题。

我认为您不能在 Ionic 事件中调用 observable 方法,所以我将方法更改为 void。目前一切都很好。


推荐阅读