Jason Jason - 1 month ago 12
TypeScript Question

'Undefined' in Angular 2 Observables and Http

I find using observables with http in angular 2 really difficult.
In the below code, I get the

in method:
value printed in console successfully. But
Main:
is
undefined
when I tried to print .

How can I get the value from
Main
?

Template code:

template:`
<input
class="form-control"
[formControl]="searchBox"
placeholder="Search Spotify artist" />
`


Component code:

export class SpotifySearchComponent {

private searchBox = new FormControl();

constructor(private _http: Http){

}

ngAfterViewInit() {
var keyups = this.searchBox
.valueChanges
.debounceTime(200)
.map(searchTerm => {
this.getResults(searchTerm);
});

var subscription = keyups.subscribe(res => console.log("Main:" + res));
}

getResults(searchTerm){
console.log("in method:" + searchTerm);
return searchTerm;
}
}

Answer

You're missing a return statement in the map block.

ngAfterViewInit() {    
    var keyups = this.searchBox
        .valueChanges
        .debounceTime(200)
        .map(searchTerm => {
            return this.getResults(searchTerm);           
        });

    var subscription = keyups.subscribe(res => console.log("Main:" + res));       
  }