我在我的打字稿代码中得到以下错误,但不确定为什么有任何想法 - 这是this.items
变量?
类型'对象'不能分配给'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 = []
响应可能是一个对象。
您将项目设置为等于对象。
您应该生成任何OR类型的项目
您应该将响应对象推送到items数组,如下所示:
this.items.push(response)
要么
this.items = [...this.items, response]
取决于你想要的。