"Type 'Object' is not assignable to type" 使用新的 HttpClient / HttpGetModule

"Type 'Object' is not assignable to type" with new HttpClient / HttpGetModule

Google's official Angular 4.3.2 doc here 之后,我能够从本地 json 文件执行一个简单的 get 请求。我想练习从 JSON 占位符站点命中一个真正的端点,但我无法弄清楚要在 .subscribe() 运算符中放入什么。我制作了一个 IUser 接口来捕获有效负载的字段,但是带有 .subscribe(data => {this.users = data}) 的行抛出错误 Type 'Object' is not assignable to type 'IUser[]'。处理这个问题的正确方法是什么?看起来很基本,但我是菜鸟。

我的代码如下:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { IUsers } from './users';

@Component({
  selector: 'pm-http',
  templateUrl: './http.component.html',
  styleUrls: ['./http.component.css']
})
export class HttpComponent implements OnInit {
  productUrl = 'https://jsonplaceholder.typicode.com/users';
  users: IUsers[];
  constructor(private _http: HttpClient) { }

  ngOnInit(): void {    
    this._http.get(this.productUrl).subscribe(data => {this.users = data});
  }

}

您实际上在这里有几个选项,但使用泛型将其转换为您期望的类型。

   // Notice the Generic of IUsers[] casting the Type for resulting "data"
   this.http.get<IUsers[]>(this.productUrl).subscribe(data => ...

   // or in the subscribe
   .subscribe((data: IUsers[]) => ...

此外,我建议在您的模板中使用自动订阅/取消订阅的异步管道,特别是如果您不需要任何花哨的逻辑,而您只是映射值。

users: Observable<IUsers[]>; // different type now

this.users = this.http.get<IUsers[]>(this.productUrl);

// template:
*ngFor="let user of users | async"

我在 Angular 文档团队,一个未完成的待办事项是更改这些文档以显示 "best practice" 访问 Http 的方式......这是通过服务。

这是一个例子:

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';

import { IProduct } from './product';

@Injectable()
export class ProductService {
    private _productUrl = './api/products/products.json';

    constructor(private _http: HttpClient) { }

    getProducts(): Observable<IProduct[]> {
        return this._http.get<IProduct[]>(this._productUrl)
            .do(data => console.log('All: ' + JSON.stringify(data)))
            .catch(this.handleError);
    }

    private handleError(err: HttpErrorResponse) {
        // in a real world app, we may send the server to some remote logging infrastructure
        // instead of just logging it to the console
        let errorMessage = '';
        if (err.error instanceof Error) {
            // A client-side or network error occurred. Handle it accordingly.
            errorMessage = `An error occurred: ${err.error.message}`;
        } else {
            // The backend returned an unsuccessful response code.
            // The response body may contain clues as to what went wrong,
            errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
        }
        console.error(errorMessage);
        return Observable.throw(errorMessage);
    }
}

组件将如下所示:

ngOnInit(): void {
    this._productService.getProducts()
            .subscribe(products => this.products = products,
                       error => this.errorMessage = <any>error);
}