'Undefined' 在 Angular 2 Observables 和 Http

'Undefined' in Angular 2 Observables and Http

我发现在 angular 2 中使用 observables 和 http 真的很困难。 在下面的代码中,我成功地在控制台中打印了 in method: 值。但是当我尝试打印 .

Main:undefined

如何从 Main 中获取值?

模板代码:

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

组件代码:

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

您在 map 块中缺少 return 语句。

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

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

您没有从 map 函数返回任何内容。应该是

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

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