gpt4 book ai didi

javascript - 如何订阅返回 rxjs observable 的类方法?

转载 作者:行者123 更新时间:2023-12-02 23:30:03 25 4
gpt4 key购买 nike

我有一个类方法,它使用来自 rxjs 的BehaviourSubject 和 fromFetch 并返回一个可观察值。我正在尝试订阅类外的方法。

我可以console.log我得到的方法AnonymousSubject {_isScalar: false, Observers: Array(0), close: 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:您在需要流的地方提供了无效的对象。您可以提供 Observable、Promise、Array 或 Iterable。

最佳答案

问题是您正在返回简单的 response.json() 您应该从 switchMap 的 if ( response.ok) block - 请参阅下面的代码 -

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

关于javascript - 如何订阅返回 rxjs observable 的类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56552952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com