角度-指定可观察的返回类型?

时间:2018-07-22 09:26:43

标签: angular typescript rxjs

我在函数中有这部分:

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.headersdata.body,认为这些属性在'object'类型上不存在。

如何让它知道一切都很好?我曾想过要输入返回值,但不能成功输入。

3 个答案:

答案 0 :(得分:3)

这与IDE不相关。只是Typescript的编译器在争论类型object没有这些属性,这是正确的。

只需将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;
});

答案 1 :(得分:3)

您的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
}

-订阅

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

答案 2 :(得分:1)

了解返回数据的类型是一个好习惯。这就是您如何为其分配https://stackoverflow.com/a/49627627/9590251

在您的情况下-创建一个接口并为返回的数据分配类型