Hypenate
Hypenate

Reputation: 2064

Inject service with global function

In all my services I have 2 methods, handleErrors and ExtractData, this violates the DRY principle.

The two methods:

  private extractData(res: Response) {
    let body = res.json();  
    return body || {};
  }

  private handleErrors(error: any): Observable<any> {
    return Observable.throw(error.json(););
  }

I want make those methods public and move them to a service which I then would inject to all my services and thus going from:

  getFoo(): Observable<IFoo[]> {
    return this._http.get(FooApi)
      .map(this.extractData)
      .catch(this.handleErrors);
  }

too:

  getFoo(): Observable<IFoo[]> {
    return this._http.get(FooApi)
      .map(this._helperService.extractData)     //<--
      .catch(this._helperService.handleErrors); //<--
  }

The error I receive on .map(this._helperService.extractData) is:

Argument of type '(res: Response) => {}' is not assignable to parameter of type '(value: Response, index: number) => {}'. Types of parameters 'res' and 'value' are incompatible. Type 'Response' is not assignable to type 'Response'. Two different types with this name exist, but they are unrelated. Property 'body' is missing in type 'Response'.

I tried adding brackets() but then I receive:

Expected 1 arguments, but got 0.

Why does it work when the method is in the same class?
How can I make it work when the method is in another class, or maybe there is a different approach I need to take?

Upvotes: 0

Views: 212

Answers (1)

Tomasz Kula
Tomasz Kula

Reputation: 16857

Add import { Response } from '@angular/http'; to your helper service.

Currently the helper service uses the lib.dom.d.ts Response interface.

Upvotes: 1

Related Questions