订阅输入值更改并请求spotify

时间:2016-10-27 15:05:10

标签: angular angular2-observables

我正在尝试使用以下代码中的Angular 2中的Observables从spotify api获取数据。

我想订阅输入值changechanges事件,该事件又发送请求以使用输入的搜索词进行spotify。

我是Observables的新手,并且真的很难用这整个嵌套的回调/可观察事物。如果有人提供有关如何正确订阅输入框并在用户输入时显示spotify结果的代码,我将不胜感激。

@Component({
  selector: 'spotify-search',
  template: `
    <h1>Spotify Search</h1>
    <input 
        class="form-control"
      [formControl]="searchBox" 
      placeholder="Search Spotify artist" />

    <div *ngFor=" let artists of results | async"> 
        {{ artists.name }} -- Followers {{artists.followers.total}} -- Popularity {{ artists.popularity }}        
    </div>
  `
})
export class SpotifySearchComponent {

  private searchBox = new FormControl();

  constructor(private _http: Http){

  }

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

    var subscription = keyups.subscribe(res => console.log(res));       
  }

  getResults(searchTerm){           
    return this._http.get('https://api.spotify.com/v1/search?q=' + searchTerm + '&type=artist')
      .map(response => {
            response.json();                                    
      }, error => console.log('Could not load artists'));            
  }  
}

1 个答案:

答案 0 :(得分:0)

我认为在你的代码中你错过了界面的实现&#34; AfterViewInit&#34;

export class SpotifySearchComponent implements AfterViewInit {...