TypeScript - Angular - gözlemlenebilir dönüş türü nasıl belirtilir?
Bir fonksiyonda bu kısmım var :
this.myservice.getComments()
.subscribe(data => {
this.post.comments = data.body;
this.post.comments_count = Number(data.headers.get('x-wp-total'));
this.post.comments_pages = Number(data.headers.get('x-wp-totalpages'));
this.content_ready = true;
});
getComments fonksiyonu :
export class myservice extends DataService {
protected url = 'my_url';
constructor( protected http: HttpClient ) {
super(http);
}
getComments(){
return this.get(
this.subUrl, true );
}
}
dataService'in ilgili kısmı :
export class DataService {
protected url: string;
constructor(protected http: HttpClient) {}
get(subUrl:string = '', needObservable = false) {
let options = {};
if(needObservable) {
options = {observe: 'response'};
}
return this.http.get(this.url + subUrl, options);
}
}
Tüm bunlar iyi çalışıyor. Sorun şu ki, IDE'm (PhpStorm) data.headers ve data.body hakkında uyarı veriyor ve bu özelliklerin 'object' türünde mevcut olmadığını iddia ediyor.
Her şeyin yolunda olduğunu ona nasıl bildirebilirim? Enter tuşuna basmayı düşündüm ama bunu başaramadım.
Cevap #1
data türünüz, http.get<T>() yönteminizden döndürülen tür olmalıdır
get(subUrl:string = '', needObservable = false) : Observable<T> {
let options = {};
if(needObservable) {
options = {observe: 'response'};
}
return this.http.get<T>(this.url + subUrl, options); // add a type that you are expecting to be returned from api
}
-subscription
this.myservice.getComments()
.subscribe((data : T) => {
this.post.comments = data.body;
this.post.comments_count = Number(data.headers.get('x-wp-total'));
this.post.comments_pages = Number(data.headers.get('x-wp-totalpages'));
this.content_ready = true;
});
Cevap #2
Bu IDE ile ilgili değil. Sadece Typescript derleyicisi, object tipinin bu özelliklere sahip olmadığını söylüyor ve haklı.
Sadece data türünü any olarak ayarlayın - data: any.
.subscribe((data: any) => {
this.post.comments = data.body;
this.post.comments_count = Number(data.headers.get('x-wp-total'));
this.post.comments_pages = Number(data.headers.get('x-wp-totalpages'));
this.content_ready = true;
});
