簡體   English   中英

如何訂閱返回可觀察到的rxjs的類方法?

[英]How to subscribe to class method that returns a rxjs observable?

我有一個使用rxjs的BehaviorSubject和fromFetch的類方法,並返回一個可觀察的對象。 我正在嘗試在課外訂閱方法。

我可以使用console.log獲得AnonymousSubject {_isScalar: false, observers: Array(0), closed: false, isStopped: false, hasError: false, …}

export class Client {
  constructor(opts) {
    ...
  }
  request(operation) {
    const option$ = new BehaviorSubject(null)
    const body = JSON.stringify({
      query: operation.query,
      variables: operation.variables
    })
    option$.next(body)

    return option$.pipe(
      switchMap(body => {
        return fromFetch(url, {
          method: 'POST',
          body,
          headers: {
            'Content-Type': 'application/json',
            ...fetchOpts.headers
          },
          ...fetchOpts
        }).pipe(
          switchMap(response => {
            if (response.ok) {
              // OK return data
              return response.json()
            } else {
              // Server is returning a status requiring the client to try something else.
              return of({
                error: true,
                message: `Error ${response.status}`
              })
            }
          }),
          catchError(err => {
            // Network or other error, handle appropriately
            console.error(err)
            return of({ error: true, message: err.message })
          })
        )
      })
    )
  }
}

我想像這樣調用方法並訂閱它

let client = new Client({...})

function handleRequest(operations) {
  let data = client.request(operations)
  data.subscribe(...)
}

當我向數據添加.subscribe ,它會引發錯誤: Uncaught TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable. Uncaught TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

問題是您要返回簡單的response.json()您應該從switchMap的if (response.ok)塊返回一個類似of(response.json())的可觀察對象-請參見下面的代碼-

export class Client {
  constructor(opts) {
    ...
  }
  request(operation) {
    const option$ = new BehaviorSubject(null)
    const body = JSON.stringify({
      query: operation.query,
      variables: operation.variables
    })
    option$.next(body)

    return option$.pipe(
      switchMap(body => {
        return fromFetch(url, {
          method: 'POST',
          body,
          headers: {
            'Content-Type': 'application/json',
            ...fetchOpts.headers
          },
          ...fetchOpts
        }).pipe(
          switchMap(response => {
            if (response.ok) {
              // OK return data
              return of(response.json())
            } else {
              // Server is returning a status requiring the client to try something else.
              return of({
                error: true,
                message: `Error ${response.status}`
              })
            }
          }),
          catchError(err => {
            // Network or other error, handle appropriately
            console.error(err)
            return of({ error: true, message: err.message })
          })
        )
      })
    )
  }
}

暫無
暫無

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

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