I'm working on switching the code to rxjs
here is my original code.
userAuth$: BehaviorSubject<ArticleInfoRes>;
async loadArticleList(articleId: number) {
try {
const data = await this.articleApi.loadArticleList(articleId);
this.userAuth$.next(data);
return data;
} catch (error) {
return error;
}
}
Subsequently, an attempt was made to convert to rxjs, but the value was not delivered properly. A value or error must be passed to the location where the loadArticleList function is used. Please tell me what's wrong
This is the code I tried to convert.
userAuth$: BehaviorSubject<ArticleInfoRes>;
loadArticleList(articleId: number) {
from(this.articleApi.loadArticleList(articleId)).subscribe(
data => {
this.userAuth$.next(data);
return data;
},
error => {
return error;
}
)
}
A value or error must be passed to the location where the loadArticleList function is used. Please tell me what's wrong
To answer your question directly, the reason why the result (i.e., value or error) isn't passed to where you use loadArticleList() is because your RxJS pipeline is not built properly. For one, adding return data; and return error; in your subscription handlers won't actually return data nor error.
To get the result, you might want to "trickle down" (streamline) that result further down the RxJS pipeline, so that subscription to that result happens in the location you speak of, to where loadArticleList() is used. This translates to moving your call to .subscribe() outside of loadArticleList(), not inside.
So, here's a proper RxJS revision:
import { tap } from "rxjs/operators";
userAuth$: BehaviorSubject<ArticleInfoRes>;
loadArticleList(articleId: number) {
return from(this.articleApi.loadArticleList(articleId)).pipe(
tap((data) => this.userAuth$.next(data)) // 👈 tap into the result to update the next userAuth$
);
}
Using the tap RxJS operator, we can grab the result of loadAarticleList(articleId), process it according to your callback function inside tap (in this case, simply update the next value of userAuth$), and then with that same grabbed result, unmodified, pass it on to whoever subscribes to loadArticleList().
Finally, to actually "pass" data or errorto the location where the loadArticleList function is used, simply subscribe there.
// in your component's .ts somwehere, probably
loadArticleList(123).subscribe(
data => { /* do as you want with the result */ },
error => { /* add your error-handling logic here */ }
);