在教程中,讲师使用 siteify api 构建 Spotify 音乐搜索。遵循讲师所做的每一步,但问题是我的数据永远不会返回,我得到未定义的信息,并且屏幕上没有显示任何内容。但是,如果我直接在浏览器中点击 api,则会显示 json 数据,但不会在我的应用程序中显示。
其实我见过很多这样的问题,但没有一个能解决我的问题。我认为这可能是一个与网络相关的问题,但是当我设置断点时,我可以在响应中看到结果,但没有任何内容加载到 View 中,未定义正在加载到控制台中
**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');
}
}
最佳答案
既然你是这样映射的:
.map((res) => { res.json() })
您需要使用return
.map((res) => { return res.json() })
或仅使用:
.map(res => res.json())
DEMO
关于angular - Http.Get() 总是在 Angular 2 中返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43456723/