Observable<{}> not assignable to type Observable

前端 未结 5 1001
自闭症患者
自闭症患者 2020-12-08 10:04

I\'m learning Angular2 and Typescript. I\'m working through the Heroes tutorial on angular.io, but applying it to a project I\'m converting from ASP.Net. I\'ve run into a pr

5条回答
  •  不思量自难忘°
    2020-12-08 10:11

    I think that your problem is located here:

    getRisks(): Observable {
      return this.http.get(this.serviceUrl)
         .map(this.extractData()) <== passing result of function
         .catch(this.handleError()); <== passing result of function
    }
    

    You could use just passing function reference:

    getRisks(): Observable {
      return this.http.get(this.serviceUrl)
         .map(this.extractData)
         .catch(this.handleError);
    }
    

    but this way you will lose this.

    Or you could use bind method to retain this:

    getRisks(): Observable {
      return this.http.get(this.serviceUrl)
        .map(this.extractData.bind(this))
        .catch(this.handleError.bind(this));
    }
    

    however you will lose type checking.

    I would leverage arrow functions to be able to use lexical this:

    getRisks(): Observable {
      return this.http.get(this.serviceUrl)
        .map(res => this.extractData(res))
        .catch(err => this.handleError(err));
    }
    

    Without it, the this variable will point to the function where the call is made, instead of the instance that contains getRisks().

提交回复
热议问题