【问题标题】:Angular - specify observable return type?Angular - 指定可观察的返回类型?
【发布时间】:2018-12-30 00:21:18
【问题描述】:

我在函数中有这部分:

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,认为这些属性在“对象”类型上不存在。

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

【问题讨论】:

    标签: angular typescript rxjs


    【解决方案1】:

    了解返回数据的类型是一个好习惯...这就是分配它的方式https://stackoverflow.com/a/49627627/9590251

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案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;
        });
        

        【讨论】:

        • 看起来不错。打字应该在括号里!谢谢。
        • 返回类型必须知道你,我不知道。任何只是一种解决方法
        猜你喜欢
        • 2018-04-11
        • 1970-01-01
        • 1970-01-01
        • 2020-06-24
        • 2016-05-03
        • 2019-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多