类型'对象'不能分配给Angular 4.x app中的'any []'

问题描述 投票:1回答:2

我在我的打字稿代码中得到以下错误,但不确定为什么有任何想法 - 这是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;
        });
 }
}
javascript angular typescript
2个回答
1
投票

做这个改变

public items = {}

那么事情是,你正在制作any类型的数组,显然响应是object类型


0
投票

这是any[]的任何项目的数组。

public items = []

响应可能是一个对象。

您将项目设置为等于对象。

您应该生成任何OR类型的项目

您应该将响应对象推送到items数组,如下所示:

this.items.push(response)

要么

this.items = [...this.items, response]

取决于你想要的。

© www.soinside.com 2019 - 2024. All rights reserved.