Angular 2 Observables中的'Undefined'和Http

时间:2016-10-27 09:01:05

标签: angular typescript angular2-observables

我发现在角度2中使用http的observable非常困难。 在下面的代码中,我成功地在控制台中打印了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;
  }  
}

2 个答案:

答案 0 :(得分: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));       
  }

答案 1 :(得分:1)

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

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

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