[英]Http.Get() always returning undefined in angular 2
按照教程,教師正在使用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');
}
}
因為您的映射如下:
.map((res) => { res.json() })
你需要使用return
.map((res) => { return res.json() })
或僅使用:
.map(res => res.json())
您的[(ngModel)]在這種情況下不起作用,因此您需要使用ElementRef來引用輸入文本框
<input type="text" name="searchStr" #input (keyup.enter)="searchMusic(input.value)" class="form-control" placeholder="Search music here..."/>
將您的方法修改為
searchMusic(searchStr:string) {
return this._spotifyservice.searchMusic(searchStr)
.subscribe(data => {
console.log(data);
this.searchResult = data;
},
error => {
console.log(error)
})
}
在您的組件中聲明一個元素ref為
@ViewChild('input') input: ElementRef;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.