简体   繁体   中英

Angular 2 rxjs switchmap returns Observable<Object>

I'm building a typescript angular 2 app and using rxjs. I am following the example here:

https://angular.io/docs/ts/latest/tutorial/toh-pt6.html#!#stq=formgroup&stp=1

All though I am trying to strongly type my return signatures with typescript. This may be my problem in that you aren't supposed to. But it seems like you should be able to.

Suppose I have service that is typed to return an Observable>.

 public search(term: string) : Observable<Array<MyModel>> { // http call }

In my component I am attempting to listen to this observable stream and return the results.

 private search = new Subject<Search>();
 results: Observable<Array<MyModel>>;

 ngOnInit() {
     this.results = this.search
        .debounceTime(400)
        .distinctUntilChanged()
        .switchMap(search => {
            return service.search(search.term); // returns Observable<Array<MyModel>>
        });
  }

This doesn't compile with the message Cannot convert type Observable<Object> to type Observable<MyModel[]>>

I don't understand why switchmap is returning an Observable instead of my type. Do I need to map it again before giving it to results? Is this a typescript typings issue with the return signature of switchmap?

Typescript might have wrong type inference, I would try one of the following:

give your handler a return type:

.switchMap((search): Observable<Array<MyModel>> => {
        return service.search(search.term); // returns Observable<Array<MyModel>>
    });

and if this doesn't work, "compromise" for changing the type of the results variable to:

 results: Observable<any>;

The error message is actually right. However, it's unclear what line caused the error without a stack trace.

In the ngOnInit() method you call:

this.results = this.search
    .debounceTime(..)
    ...

This chain of operators always returns an Observable which is not as the result property expects ( Observable<Array<MyModel>> ) because the Subject 's generic is Search .

Operator switchmap() returns always an Observable . Its return type has nothing to do with the callable.

You should be able to solve this by simply typecasting the result:

this.results = Observable<MyModel[]>this.search
    .debounceTime(..)
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM