Jer*_*olo 10 rxjs typescript angular
我在一个函数中有这部分:
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;
});
Run Code Online (Sandbox Code Playgroud)
该getComments函数:
export class myservice extends DataService {
protected url = 'my_url';
constructor( protected http: HttpClient ) {
super(http);
}
getComments(){
return this.get(
this.subUrl, true );
}
}
Run Code Online (Sandbox Code Playgroud)
dataService 的相关部分:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
所有这些都运作良好。问题是,我的 IDE (phpstorm) 抱怨data.headersand data.body,认为这些属性不存在于类型“对象”上。
如何让它知道一切都很好?我想过输入 return 但没有成功。
Ami*_*ani 12
你data的类型应该是从你的返回的类型http.get<T>()
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
}
Run Code Online (Sandbox Code Playgroud)
-订阅
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;
});
Run Code Online (Sandbox Code Playgroud)
这与IDE无关。只是 Typescript 的编译器认为 typeobject没有这些属性,这是对的。
只需将类型设置data为any- 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;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9269 次 |
| 最近记录: |