网站搜索

typescript - Angular 2 Observables 和 Http 中的 'Undefined'


我发现使用 Angular 2 中的 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;
  }  
}

答案#1

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

答案#2

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

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

或

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