首页 > 解决方案 > rxjs v6 和 rxjs/operators 的错误

问题描述

我在实现 rxjs v6 和 rxjs/operators 时遇到问题:

import { Observable } from 'rxjs';
import { Subject } from 'rxjs';
import { startWith, debounceTime } from 'rxjs/operators';

export class ProductListComponent implements OnInit {

    public products$: Observable<Product[]>;
    public searchTerm: string = '';

    private searchSubject: Subject<string> = new Subject();
    private reloadProductsList: Subject<void> = new Subject();

    constructor(private productService: ProductService) { }

    ng OnInit() {
        this.products$ = this.searchSubject
            .pipe(startWith(this.searchTerm), debounceTime(300));
    }
    ...
}

具体错误在于this.products$in ngOnInit()。这是错误:

Type 'Observable<string | Product[]>' is not assignable to type 'Observable<Product[]>'.
Type 'string | Product[]' is not assignable to type 'Product[]'.
Type 'string' is not assignable to type 'Product[]'

这个错误让我很困惑。你能帮忙吗?

标签: angularrxjs

解决方案


是的,问题出在startWith(this.searchTerm). 你不能从那开始,因为它是一个字符串并且this.products$Observable<Product[]>;. 还有,this.searchSubjectSubject<string>

你确定不是this.products$ = this.productService.getProducts();这样的吗?


推荐阅读