从Http服务

时间:2016-04-21 15:22:26

标签: typescript angular angular2-http

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

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都是红色的。 (未解析的变量)但代码编译并运行。

enter image description here

这让我相信这一定是错误的做法。如果没有未解决的变量,我怎样才能做到这一点。

2 个答案:

答案 0 :(得分: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);
    }

答案 1 :(得分:0)

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

{{1}}