且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

输入'Observable< {}>不可分配给“可观察"类型

更新时间:2022-11-30 12:10:33

我无法告诉您确切的问题,但是我也为这几次苦苦挣扎!

I can't tell you that exact problem, but I struggled over this few times too!

.switchMap()存在问题.Idk,如果是打字稿问题或其他问题.也许只是打字文件是错误的..

It's a problem with .switchMap(). Idk if it's an typescript problem or what.. Maybe just the typings file is bad..

您必须投射它:

ngOnInit(): void {
    this.locations = <Observable<Location[]>>this.searchTerms // <- ERROR HERE
        .debounceTime(300)
        .distinctUntilChanged()
        .switchMap(term => term
            ? this.locationSearchService.search(term)
            : Observable.of<Location[]>([]))
        .catch(error => {
            console.log(error);
            return Observable.of<Location[]>([]);
        })
}

或者(如上所述)将函数 switchMap() catch()与类型声明一起使用,如下所示:

Or (as you mentioned) use your functions switchMap() and catch() with a type declaration, like this:

ngOnInit(): void {
    this.locations = this.searchTerms // <- ERROR HERE
        .debounceTime(300)
        .distinctUntilChanged()
        .switchMap<Observable<Location[]>>(term => term
            ? this.locationSearchService.search(term)
            : Observable.of<Location[]>([]))
        .catch<Observable<Location[]>>(error => {
            console.log(error);
            return Observable.of<Location[]>([]);
        })
}