Angular 2'de aşağıdaki kodu yazdım:
this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
subscribe((res: Response) => {
console.log(res);
})
Konsolda aldığım yanıtı yazdırdığımda:
Kodda yanıttaki body alanına erişmek istiyorum. body' alanı alt çizgi ile başlıyor, bu da özel bir alan olduğu anlamına geliyor. Bunu 'console.log(res._body)' olarak değiştirdiğimde bir hata alıyorum.
Burada bana yardımcı olabilecek herhangi bir getter fonksiyonu biliyor musunuz?
İşte bir get
http çağrısı örneği:
this.http
.get('http://thecatapi.com/api/images/get?format=html&results_per_page=10')
.map(this.extractData)
.catch(this.handleError);
private extractData(res: Response) {
let body = res.text(); // If response is a JSON use json()
if (body) {
return body.data || body;
} else {
return {};
}
}
private handleError(error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
.request()yerine
.get()` ifadesine dikkat edin.
İhtiyacınız olması ve elinizde olmaması ihtimaline karşı size ekstra extractData
ve handleError
yöntemleri de sunmak istedim.
Yanıt verileri JSON dizesi biçimindedir. Uygulama, response.json() işlevini çağırarak bu dizeyi JavaScript nesnelerine ayrıştırmalıdır.
this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
.map(res => res.json())
.subscribe(data => {
console.log(data);
})
https://angular.io/docs/ts/latest/guide/server-communication.html#!#extract-data
Doğrudan _body
nesnesine başvuramaz mısınız? Görünüşe göre bu şekilde kullanıldığında herhangi bir hata döndürmüyor.
this.http.get('https://thecatapi.com/api/images/get?format=html&results_per_page=10')
.map(res => res)
.subscribe(res => {
this.data = res._body;
});