我想customers通過get Http呼叫從我的后端獲取串列。但我無法申報array的customers我component。
我有這樣的customer.interface.ts
export interface Customer {
_id?: string,
name: string,
email: string,
phone?: string,
address?: string,
age?: number
}
我有 http.service.ts
get = (url: string): Observable<any> => {
return this.http.get(this.createUrl(url), { headers: this.getHeaders() });
}
在我的 customer.service.ts
getCustomers(): Observable<Customer[]>{
return this._http.get(ApiConstants.getCustomers);
}
在我的 customer.component.ts
customers$: Observable<Customer[]> = [];
ngOnInit(){
this.customers$ = this.customerService.getCustomers();
}
現在它customers$: Observable<Customer[]> = []在編譯時在編輯器中給了我這樣的錯誤。
Type 'never[]' is missing the following properties from type 'Observable<Customer[]>': isScalar, source, operator, lif and 5 more
這里有什么問題?
uj5u.com熱心網友回復:
的型別customers$是一個Observable,所以你不能給它分配一個空陣列。所以你根本不需要定義它。這樣就夠了->
customers$!: Observable<Customer[]>;
!如果您的"strictPropertyInitialization"intsconfig.json設定為true,則添加此項,否則您可以省略它。!當您不立即宣告財產時,這是需要的。您可以設定"strictPropertyInitialization"為false然后省略!. 您可以查看Property '...' has no initializer 并且未在建構式中明確分配
此外,當您需要創建一個Observableout 的東西時,您可以使用ofRxJS 運算子將引數轉換為可觀察序列。https://rxjs.dev/api/index/function/of
一個補充是在之后添加強制轉換.get以更清楚地了解型別。
getCustomers(): Observable<Customer[]> {
return this._http.get<Customer[]>(ApiConstants.getCustomers);
}
這個問題的答案可能會對你Typescript有所幫助:Type X 缺少來自 type Y 長度、pop、push、concat 等 26 個屬性的以下屬性。[2740]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/409677.html
標籤:
上一篇:如何附加到編譯時常量
