"类型'对象'不能分配给新的HttpClient/HttpGetModule"

mid*_*oir 14 api http-get angular

按照Google的官方Angular 4.3.2文档,我能够get从本地json文件做一个简单的请求.我想练习从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});
  }

}
Run Code Online (Sandbox Code Playgroud)

Mar*_*.io 33

实际上你在这里有几个选项,但是使用泛型将它转换为你期望的类型.

   // 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[]) => ...
Run Code Online (Sandbox Code Playgroud)

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

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

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

// template:
*ngFor="let user of users | async"
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你,铸造工作很棒! (2认同)

Deb*_*ahK 16

我在Angular doc团队和一个开放的todo项目是改变这些文档,以显示访问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);
    }
}
Run Code Online (Sandbox Code Playgroud)

该组件将如下所示:

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