我尝试根据我的需要调整 ngx-chips 的工作示例。这是 onRemoving 方法示例的样子:
public onRemoving(tag: TagModel): Observable<TagModel> {
const confirm = window.confirm('Do you really want to remove this tag?');
return Observable
.of(tag)
.filter(() => confirm);
}
现在,我不想使用 windows.confirm
,而是使用具有 AskQuestion
方法和以下签名的自定义组件:
AskQuestion(question: string, yesCallback: () => void, noCallback?: () => void): void {
所以现在我有多个回调,但 ngx-chips 组件期望我返回一个可观察对象。我尝试使用 bindCallback
方法将回调转换为可观察对象:
public onRemoving(tag: TagModel): Observable<TagModel> {
const choiceCallback = (choice: boolean): TagModel=> {
if (choice)
return tag;
};
this.questionService.AskQuestion("Remove item?", () => choiceCallback(true), () => choiceCallback(false))
return Observable.bindCallback(choiceCallback);
}
但看起来我做错了。有什么想法吗?
最佳答案
bindCallback()
的定义如下:
Give it a function f of type f(x, callback) and it will return a function g that when called as g(x) will output an Observable.
并且您的用法不符合此描述。 choiceCallback()
不返回返回 observable 的函数。
改为使用 Observable 构造函数:
public onRemoving(tag: TagModel): Observable <TagModel> {
return Observable.create(observer => {
const choiceCallback = (choice: boolean) => {
if (choice) {
observer.next(tag);
}
observer.complete();
};
this.questionService.AskQuestion("Remove item?", () => choiceCallback(true), () => choiceCallback(false));
});
}
关于javascript - 基于回调返回 Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47550423/