【发布时间】: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