javascript – 一旦Rx.Observable发生错误,ValueChanges就会停止工作

我正在遵循Angular 2应用程序中的一些Rx.Observable教程并使用AutoComplete风格的系统.

当我键入字段时,valueChanges事件从Angular 2 FormControl触发.

这被链接到Observable,它正在针对JSON端点发出HTTP请求.

端点返回404状态的那一刻,valueChanges事件停止工作.

我可以看到我的订阅方法中的错误,但不确定最好的技术是什么,以恢复和继续.

我也有点困惑为什么KeyUp或ValueChange事件会停止触发.

样本价值变化 – 可观察链

this.userNameControl
    .valueChanges
    .do(r => {
            // As soon as a 404 status is thrown from getGitHuybUser$, all value change (keyup) events stop working
            console.log
        }
    )
    .switchMap(userName => {
        return this.getGitHubUser$(userName);
    })
    .catch(err => {
        return Observable.of(err)
    })
    .subscribe(v => {
            console.log(v);
        },
        (err) => {
            // As soon ass there is a 404 status, I end up here
            console.log(err);
        },
        () => {
            console.log('Complete');
        });

getGitHubUser$(username) {
    return this.http
        .get(`https://api.github.com/users/${username}`)
}

HTML表单控件

<input type="text" [value]="userName" [formControl]="userNameControl" />

我尝试在catch中返回Observable.empty()和Observable.never()

.catch(err => {
    // Observable.of(err)
    // return Observable.empty();
    return Observable.never();
})

结果是subscribe方法调用了我的完整方法,但仍然没有触发valueChanges.

解决方法:

弄清楚我的问题,我挂起的.switchMap()的.catch()确实需要挂起this.getGitHubUser $(userName)

this.userNameControl
    .valueChanges
    .do(r => {
            // As soon as a 404 status is thrown from getGitHuybUser$, all value change (keyup) events stop working
            console.log(r);
        }
    )
    .switchMap(userName => {
        console.log('GET GIT HUB USER');

        return this.getGitHubUser$(userName)
            .catch(err => {
                console.log('CATCH INNER');
                console.log(err);
                return Observable.of(err)
            })
    })
    // .catch(err => {
    //     // THIS CODE IS NOT NEEDED
    //     console.log('CATCH');
    //     console.log(err);
    //     return Observable.never(); // Observable.of(err)
    // })
    .subscribe(v => {
            console.log('SUCCESS');
            console.log(v);
        },
        (err) => {
            console.log('ERROR');
            console.log(err);
        },
        () => {
            console.log('COMPLETE');
        });
上一篇:javascript – RxJS:如何包装和观察字符串的变化?


下一篇:IRequest