0

One of my services has a method with this implementation:

public getCrawls(page: number): Observable<ICrawl[]>{
        return this._http.get(this._crawlsURL + page)
            .map((res: Response) => {
                return {
                    crawls: <ICrawl[]>res.json(),
                    headers: res.headers
                }
            })
            .catch(this.handleError);
    }

I am doing this as opposed to .map((res: Response) => <ICrawl[]>res.json())

So in the consumer component I can also access the headers to make my paginator work:

getCrawls(page: number): void {
        this._crawlsService.getCrawls(page)
            .subscribe(
                res => {
                    this.crawls = res.crawls;
                    this.totalItems = res.headers.get('X-Records');
                },
                error => this.errorMessage = <any>error);
    }

This works, but both res.crawls and res.headers are red in WebStorm. (unresolved variables) but the code compiles and works.

enter image description here

Which brings me to be believe this must be the wrong way of doing this. How can I achieve this without having unresolved variables.

makeitmorehuman
  • 11,287
  • 3
  • 52
  • 76

2 Answers2

1

You've typed your Observable incorrectly. You have Observable<ICrawl[]>, you need:

interface ICrawlResponse {
    crawls: ICrawl[];
    headers: Headers;
}

public getCrawls(page: number): Observable<ICrawlResponse>{
        return this._http.get(this._crawlsURL + page)
            .map((res: Response) => {
                return {
                    crawls: <ICrawl[]>res.json(),
                    headers: res.headers
                }
            })
            .catch(this.handleError);
    }
chrisbajorin
  • 5,993
  • 3
  • 21
  • 34
0

I think that you simply need to define the type of the object you expect in the callback:

getCrawls(page: number): void {
  this._crawlsService.getCrawls(page)
        .subscribe(
          res:{crawls:ICrawl[],headers:Headers} => { // <------
            (...)
          }
        );
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360