2

我发现在 Angular 2 中使用带有 http 的 observables 真的很困难。在下面的代码中,我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;
  }  
}
4

2 回答 2

2

return在块中缺少一条语句map

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

    var subscription = keyups.subscribe(res => console.log("Main:" + res));       
  }
于 2016-10-27T09:06:14.840 回答
1

你没有从你的map函数中返回任何东西。它应该是

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

或者

.map(searchTerm => this.getResults(searchTerm))
于 2016-10-27T09:09:41.463 回答