[英]Type 'Object' is not assignable to type 'any[]' in Angular 4.x app
我在打字稿代碼中收到以下錯誤,但不確定為什么會有任何想法 - 這是this.items
變量?
類型“Object”不可分配給類型“any[]”。 “對象”類型可分配給很少的其他類型。 您是想改用“any”類型嗎?
export class GifpickerComponent implements OnInit {
public searchTerm : FormControl = new FormControl();
public items = [];
constructor(private gifpickerService: GifpickerService){
this.searchTerm.valueChanges
.subscribe(data => {
this.gifpickerService.search(data).subscribe(response =>{
console.log('subscribe', response);
this.items = response; /* line picked up in error */
})
})
}
/* 按要求提供服務 */
import { Injectable } from '@angular/core';
import { ApiService } from "../../services/api.service";
import { HttpClient, HttpParams, HttpResponse} from '@angular/common/http';
@Injectable()
export class GifpickerService {
constructor(
private http: HttpClient,
private apiService: ApiService
) {}
search(term){
console.log('term', term);
let url = this.apiService.getApiUrl('gif/search');
let params = new HttpParams()
.set('q', String(term))
.set('results_only', '1');
return this.http.get(url, {params: params})
.map(response => {
return response;
});
}
}
做這個改變
public items = {}
那么事情是,你正在將項目作為any
類型的數組,顯然響應是object
類型
這是任何項any[]
的數組。
public items = []
響應可能是一個對象。
您正在將項目設置為等於一個對象。
您應該制作任何類型的物品或
您應該像這樣將響應對象推送到 items 數組:
this.items.push(response)
或者
this.items = [...this.items, response]
取決於你想要什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.