【问题标题】:How to subscribe to class method that returns a rxjs observable?如何订阅返回 rxjs observable 的类方法?
【发布时间】:2019-10-26 10:07:43
【问题描述】:

我有一个类方法,它使用来自 rxjs 的 BehaviorSubject 和 fromFetch 并返回一个 observable。我正在尝试订阅课外的方法。

我可以控制台记录我得到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.

【问题讨论】:

  • 我希望这只是发布此代码时的拼写错误。不过,想确认一下 - 你试过 const option$ = new BehaviorSubject<any>(null); BehaviorSubject 必须是具有初始值的类型。
  • 是的,这是一个错字,谢谢。我更正了。

标签: javascript rxjs es6-class


【解决方案1】:

问题是您返回简单的response.json() 您应该从switchMap 的if (response.ok) 块返回一个类似of(response.json()) 的observable - 请参见下面的代码 -

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 })
          })
        )
      })
    )
  }
}

【讨论】:

  • 就是这样。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 2018-12-10
  • 2016-12-20
  • 2017-02-17
  • 2018-09-01
相关资源
最近更新 更多