0

我的一项服务有一个具有此实现的方法:

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

我正在这样做而不是.map((res: Response) => <ICrawl[]>res.json())

因此,在消费者组件中,我还可以访问标题以使我的分页器工作:

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

这可行,但两者在 WebStorm 中都是红色的res.crawlsres.headers未解决的变量),但代码编译并工作。

在此处输入图像描述

这让我相信这一定是错误的做法。在没有未解决的变量的情况下如何实现这一点。

4

2 回答 2

1

您输入的 Observable 错误。你有Observable<ICrawl[]>,你需要:

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);
    }
于 2016-04-21T16:25:45.990 回答
0

我认为您只需要在回调中定义您期望的对象的类型:

getCrawls(page: number): void {
  this._crawlsService.getCrawls(page)
        .subscribe(
          res:{crawls:ICrawl[],headers:Headers} => { // <------
            (...)
          }
        );
于 2016-04-21T16:19:13.250 回答