Angular 9错误=可分配给其他类型很少的类型

时间:2020-07-17 11:00:59

标签: angular

我创建了以下简单的数据源服务,该服务从后端API返回一个引号列表以显示在表中:

export class QuoteDataSource implements DataSource<Quote> {

    private quotesSubject = new BehaviorSubject<Quote[]>([]);
    private loadingSubject = new BehaviorSubject<boolean>(false);

    constructor(private quoteService: QuoteService) {}

    connect(collectionViewer: CollectionViewer): Observable<Quote[]> {
        return this.quotesSubject.asObservable();
    }

    disconnect(collectionViewer: CollectionViewer): void {
        this.quotesSubject.complete();
        this.quotesSubject.complete();
    }

    loadQuotes() {
        this.quoteService.getQuotes().pipe(
            finalize(() => this.loadingSubject.next(false))
        )
        .subscribe(quotes => this.quotesSubject.next(quotes));
    }
}

但是,编译器在生成过程中返回以下错误:

 The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
        Type 'Object' is missing the following properties from type 'Quote[]': length, pop, push, concat, and 26 more.

    31         .subscribe(quotes => this.quotesSubject.next(quotes));``

因此看起来问题在于以下行:

.subscribe(quotes => this.quotesSubject.next(quotes));

我没有运气就尝试了以下替代方法:

.subscribe(quotes => this.quotesSubject.next(Quote[]));

还有:

.subscribe(quotes => this.quotesSubject.next(Quote));

下面是this.quoteService.getQuotes()的函数,该函数返回引号的JOSN数组:

    getQuotes() {
        const url = `${environment.apiUrl}/quotes/list`;

        return this.http.get(url, {}).pipe(
            map( res => res)
        );
    }

我看不到我在做什么错,但希望有人能做到。

Musaffar

2 个答案:

答案 0 :(得分:1)

基于反馈,将getQuotes函数重写为以下内容解决了该问题:

    getQuotes(): Observable<Quote[]> {
        const url = `${environment.apiUrl}/quotes/list`;
        return this.http.get<Quote[]>(url, {});
    }

Musaffar

答案 1 :(得分:1)

您可以删除pipe运算符,因为您不想处理响应。

getQuotes(): Observable<Quote[]> {

        const url = `${environment.apiUrl}/quotes/list`;

        return this.http.get(url, {});
 }