【发布时间】:2017-04-17 17:56:04
【问题描述】:
按照教程,讲师正在使用 spotify api 构建 Spotify 音乐搜索。遵循教练所做的每一步,但问题是我的数据永远不会回来,我没有定义,屏幕上什么也没有。但是,如果我直接在浏览器中点击 api,则会显示 json 数据,但不会显示在我的应用中。
其实我见过很多这样的问题,但没有一个能解决我的问题。我认为这可能是与网络相关的问题,但是当我设置断点时,我可以在响应中看到结果,但没有任何内容加载到视图中,未定义正在加载到控制台中
**search.component.html**
<h1>Need Music?</h1>
<p class="lead">
Use the ngSpotify app to browse new releases of your favorite songs. See what your favorite artistes are up to.
</p>
<form>
<div class="form-group">
<input type="text" name="searchStr" [(ngModel)]="searchStr" (keyup.enter)="searchMusic()" class="form-control" placeholder="Search music here..."/>
</div>
</form>
**search.component.ts**
import { Component, OnInit } from '@angular/core';
import { SpotifyService } from '../../Services/spotify.service';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
constructor(private _spotifyservice: SpotifyService) { }
searchStr: string;
searchResult;
searchMusic() {
return this._spotifyservice.searchMusic(this.searchStr)
.subscribe(data => {
console.log(data);
this.searchResult = data;
},
error => {
console.log(error)
})
}
ngOnInit() {
}
}
**spotify.service.ts**
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Observable } from 'rxjs/Rx'
@Injectable()
export class SpotifyService {
private searchUrl: string;
constructor(private _http: Http) { }
searchMusic(str: string, type = 'artist') {
this.searchUrl = `http://api.spotify.com/v1/search?query=${str}&offset=0&limit=20&type=${type}&market=US`
return this._http.get(this.searchUrl)
.map((res) => { res.json() })
.catch(this.handleError);
}
handleError(error: Response) {
return Observable.throw(error || 'server error');
}
}
【问题讨论】:
标签: angular angular2-services angular-http angular2-observables