加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular – 指定可观察的返回类型?

发布时间:2020-12-17 07:06:59 所属栏目:安全 来源:网络整理
导读:我在函数中有这个部分: 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.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函数:

export class myservice extends DataService {
  protected url = 'my_url';

  constructor( protected http: HttpClient ) {
    super(http);
  }

  getComments(){
    return this.get(
      this.subUrl,true );
  }
}

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);
  }
}

所有这一切都运作良好.问题是,我的IDE(phpstorm)抱怨data.headers和data.body,认为这些属性在’object’类型上不存在.

如何让它知道一切都很好?我想过键入返回但没有成功.

解决方法

您的数据类型应该是从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
}

-订阅

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;
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读