[英]Use data from one observable in another and then return result as other observable
[英]return result from observable in JS
我有一個具有 observable 對象的函數,我需要返回我在這個函數中使用的 fetch 的值。 但是我不知道為什么當我顯示結果時我不能返回結果它完全沒問題但是當我嘗試返回它時它是空的。
我檢查了一些類似的問題,但它們非常復雜,而且它們與我的情況不符,而且在嘗試了其中的一兩個之后,問題仍然存在。
function getRandomQuote() {
const obs$ = Observable.create(async(observer) => {
const result = await fetch(RANDOM_QUOTE_API_URL)
.then(Response => Response.json())
.then(data => data.content)
observer.next(result)
console.log(result)
})
return obs$.subscribe(x => { return x })
}
我嘗試僅在訂閱部分內使用 return 但它不起作用,在類似的情況之一中,他們試圖返回我嘗試過但仍然無法正常工作的外部部分
我是 observable 和 JavaScrip 的新手,我只需要返回這個值並在另一個函數中使用它。 謝謝你
除了Subscription
之外,您應該返回Observable
function getRandomQuote() {
return Observable.create(async(observer) => {
const result = await fetch(RANDOM_QUOTE_API_URL)
.then(Response => Response.json())
.then(data => data.content)
observer.next(result)
})
}
//usage
getRandomQuote().subscribe(console.log)
或者有defer()
和from()
運算符可以幫助您將承諾轉換為可觀察的
getRandomQuote=()=>defer(()=>from(fetch(RANDOM_QUOTE_API_URL)
.then(Response => Response.json())
.then(data => data.content))
//usage
getRandomQuote().subscribe(console.log)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.