我有一些代碼,但 angular 13 string[] 出錯
'(string | undefined)[]' 型別的引數不能分配給'string[]' 型別的引數。
在我的產品串列中
ngOnInit(): void {
this._getPro();
this._getCate();
}
private _getPro(categoriesFilter?: string[]) {
this.proService.getProducts(categoriesFilter).subscribe((pros) => {
this.products = pros;
});
}
private _getCate() {
this.catService.getCategories().subscribe((cate) => {
this.categories = cate;
});
}
categoryFilter() {
const selectedCategories = this.categories
.filter((cate) => cate.checked)
.map((cate) => cate.id);
this._getPro(selectedCategories);
}
}
在我的產品服務中
//get all
getProducts(categoriesFilter?: string[]): Observable<Product[]> {
let params = new HttpParams();
if (categoriesFilter) {
params = params.append('categories', categoriesFilter.join(','));
}
return this.http.get<Product[]>(this.apiURLProducts, { params: params });
}
這個錯誤在這里
uj5u.com熱心網友回復:
您可以添加另一個過濾條件以確保id在每個類別上設定屬性,并使過濾函式成為型別保護謂詞函式:
TS游樂場
categoryFilter() {
const selectedCategories = this.categories
.filter((c): c is typeof c & {
checked: true;
id: string;
} => Boolean(c.checked && c.id))
.map(({id}) => id);
this._getPro(selectedCategories);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/468671.html
