[英]How to return a subscription in angular
您如何在 Angular 中返回在可注入对象上调用的订阅?
所以我一开始花了一个小时才弄明白的事情是这样的:
returnURLNotes(): Observable<any> {
return this.store.select(selectDentureDesignNotes).subscribe((notes) => {
if (
notes &&
notes[this._CANVAS_NAME] &&
notes[this._CANVAS_NAME].length > 0
) {
return notes[this._CANVAS_NAME];
}
});
}
看到第一个返回了吗? 我刚刚返回了store.selector
并且这种方法不起作用。 因为内部返回将不能用作returnURLs
方法的返回值。
所以这是我的解决方案。 它正在工作,但我不知道这是否是正确的方法。
returnURLNotes(): any {
let URLs = {};
const URLNotes$ = this.store.select(selectDentureDesignNotes);
URLNotes$.subscribe((notes) => {
if (
notes &&
notes[this._CANVAS_NAME] &&
notes[this._CANVAS_NAME].length > 0
) {
URLs = notes[this._CANVAS_NAME];
}
});
return URLs;
}
但我不认为这是正确的方法,因为 JS 单线程或“异步”。
您的第一个示例显示您正在尝试返回一个 observable。 这就是您将如何使用 rxjs 使用您提供的内容来做到这一点。 这利用了 rxjs filter和map 。 您可能不想直接返回订阅,而是订阅您的函数返回的 observable。
returnURLNotes(): Observable <any> {
return this.store.select(selectDentureDesignNotes).pipe(
filter(notes => notes &&
notes[this._CANVAS_NAME] &&
notes[this._CANVAS_NAME].length > 0),
map(notes => notes[this._CANVAS_NAME])
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.