"Тип" Объект "не присваивается типу" с новым HttpClient/HttpGetModule
Следуя официальному документу 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});
}
}
Ответы
Ответ 1
На самом деле у вас есть несколько вариантов, но используйте дженерики, чтобы привести его к ожидаемому типу.
// 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
Я нахожусь в команде doc Angular, и один открытый объект 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);
}
}
Компонент будет выглядеть следующим образом:
ngOnInit(): void {
this._productService.getProducts()
.subscribe(products => this.products = products,
error => this.errorMessage = <any>error);
}