簡體   English   中英

將rxjs 5重構為rxjs 6代碼-retryWhen

[英]Refactoring rxjs 5 to rxjs 6 code - retryWhen

我已經用rxjs 5表示法編寫了此服務代碼:

      constructor(private _authService: AuthService) {
    this._ws$ = WebSocketSubject.create<any>({
      url: WS_URL,
      protocol: this._authService.token
    });

    this._ws$.retryWhen(errors => {
        // switchMap to retrieve the source error
        return errors.switchMap(sourceErr => {
            console.log('Retry WS.', sourceErr);
            return Observable.timer(1000).map(() => Observable.of(true));
          }
        );
      }
    ).subscribe(
      msg => {
        if ('channel_name' in msg) {
          console.log('Channel name', msg.channel_name);
          this._channelName = msg.channel_name;
          this._authService.channelName = msg.channel_name;
        }
        this.subject$.next(msg);
        console.log(msg);
      },
      err => {
        console.log(err);
        this.subject$.error(err);
      },
      () => this.subject$.complete()
    );
  }

我正在嘗試將其重構為rxjs 6有效代碼,而我現在得到了這個:

constructor(private _authService: AuthService) {
this._ws$ = WebSocketSubject.create({
  url: WS_URL,
  protocol: this._authService.token
});

retryWhen(() => {
    // switchMap to retrieve the source error
    return switchMap(() => {
        return timer(1000).pipe(map(() => of(true)));
      }
    );
  }
).subscribe(
  msg => {
    if ('channel_name' in msg) {
      this._channelName = msg.channel_name;
      this._authService.channelName = msg.channel_name;
    }
    this.subject$.next(msg);
  },
  err => {
    this.subject$.error(err);
  },
  () => this.subject$.complete()
);

但是我收到以下錯誤:

TS2345: Argument of type '() => OperatorFunction<{}, Observable<boolean>>' is not assignable to parameter of type '(errors: Observable<any>) => Observable<any>'.
    Type 'OperatorFunction<{}, Observable<boolean>>' is not assignable to type 'Observable<any>'.
    Property '_isScalar' is missing in type 'OperatorFunction<{}, Observable<boolean>>'.

我無法弄清楚在這里使用retryWhen函數的最佳方法是什么以及如何在其中使用WebSocketSubject。

以上代碼在Rxjs 6中的實現類似於以下內容

 this._ws$.pipe(
  retryWhen(errors =>
    errors.pipe(
      tap(val => console.log('Retry WS.', val)),
      delay(1000)
    )
  )).subscribe( msg => {
    if ('channel_name' in msg) {
      this._channelName = msg.channel_name;
      this._authService.channelName = msg.channel_name;
    }
    this.subject$.next(msg);
  },err => {
    this.subject$.error(err);
  },() => this.subject$.complete()
  );

有關使用Rxjs 6時重試的更多信息,請參考此處。
https://www.learnrxjs.io/operators/error_handling/retrywhen.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM