简体   繁体   English

如何订阅返回可观察到的rxjs的类方法?

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

I have a class method that uses BehaviorSubject and fromFetch from rxjs and returns an observable. 我有一个使用rxjs的BehaviorSubject和fromFetch的类方法,并返回一个可观察的对象。 I'm trying to subscribe to method outside of class. 我正在尝试在课外订阅方法。

I can console.log the method I get AnonymousSubject {_isScalar: false, observers: Array(0), closed: false, isStopped: false, hasError: false, …} 我可以使用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 })
          })
        )
      })
    )
  }
}

I'm want to call method and subscribe to it like so 我想像这样调用方法并订阅它

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

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

When I add .subscribe to data it throws error: Uncaught TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable. 当我向数据添加.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.

Problem is that you are returning simple response.json() You should return an observable like of(response.json()) from switchMap's if (response.ok) block - See the code below - 问题是您要返回简单的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