Jason
Jason

Reputation: 1059

'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;
  }  
}

Upvotes: 2

Views: 144

Answers (2)

Robby Cornelissen
Robby Cornelissen

Reputation: 97120

You're not returning anything from your map function. It should be either

.map(searchTerm => {
    return this.getResults(searchTerm);           
}

or

.map(searchTerm => this.getResults(searchTerm))

Upvotes: 1

Alexander Ciesielski
Alexander Ciesielski

Reputation: 10824

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));       
  }

Upvotes: 2

Related Questions