从 Http 服务返回映射 object 的常见模式

Common pattern for returning a mapped object from Http service

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

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())

所以在消费者组件中,我还可以访问 headers 来使我的分页器工作:

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

这有效,但 res.crawlsres.headers 在 WebStorm 中都是红色的。 (未解决的变量)但代码可以编译并运行。

这让我相信这一定是错误的做法。我怎样才能在没有未解决的变量的情况下实现这一目标。

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

getCrawls(page: number): void {
  this._crawlsService.getCrawls(page)
        .subscribe(
          res:{crawls:ICrawl[],headers:Headers} => { // <------
            (...)
          }
        );

您输入的 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);
    }