0

I'm setting up a search call in my app and I'm getting the following error:

Type 'Observable' is not assignable to type 'Observable'. Type 'User' is not assignable to type 'User[]'. Property 'length' is missing in type 'User'.

Those messages are clear and I understand them, but I don't understand why I'm getting them. Here is the relevant code.

searchResults: Observable<Array<User>>;


constructor(fb:FormBuilder, private _userService: UserService){
    this.currentUser = JSON.parse(localStorage.getItem('user'));
    this.searchResults = this.searchTerm.valueChanges.debounceTime(400).distinctUntilChanged()
    .switchMap(searchTerm => this.userSearch(searchTerm));

};    

private userSearch(searchTerm: string): Array<User>{
    this._userService.getUsers(this.currentUser.UserId, this.currentUser.Token).then(
        data => {
            //loader.dismiss();
            if (data) {
                return data as Array<User>;
            } else {
                //This really should never happen
                console.error('Error retrieving users data: Data object is empty');
            }
        },
        error => {
            //loader.dismiss();                
            console.error('Error retrieving users data');
            console.dir(error);
            return error as Array<User>;
        }
    );

    return new Array<User>();
}

To me the types should match up, but they obviously don't and I'm stumped as to why. My userSearch function returns an array of Users which means the the Observable should be of that type also, but somehow its coming back as a single user. Any help is appreciated.

Maciej Treder
  • 9,856
  • 4
  • 40
  • 67
HarvP
  • 180
  • 2
  • 13
  • You are missing the fundamental concepts of how you should work with asynchronous services in javascript. Once you understand that then the above will make more sense. Looking at your code it seem you are confused on where data can be returned from. Calling `_userService.getUsers` does not do anything in your code above, you cant return data from your `then`, you should assign it to something. The method `userSearch` should probably not return anything. Again, read through the duplicate and this will make more sense. – Igor May 24 '17 at 16:06
  • Which line specifically are you getting the error on? It's likely because the result of some of your Observable are typed differently, which we can't see here – joh04667 May 24 '17 at 16:09
  • I see now that I should just make the call to getUsers in the switchMap function instead of in a separate function. I do understand the fundamental concepts of asynchronous services by the way. – HarvP May 24 '17 at 16:13

0 Answers0