代码之家  ›  专栏  ›  技术社区  ›  midnightnoir

使用新的HttpClient/HttpGetModule,“类型‘Object’不可分配给类型”

  •  17
  • midnightnoir  · 技术社区  · 7 年前

    Google's official Angular 4.3.2 doc here get .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});
      }
    
    }
    
    2 回复  |  直到 7 年前
        1
  •  41
  •   Mark Pieszak - Trilon.io johnkavanagh    5 年前

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

       // 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"
    
        2
  •  16
  •   DeborahK    7 年前

    下面是一个示例:

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