类型 'never[]' 缺少类型 'Observable<Customer[]>' 中的以下属性



我想通过getHttp调用从后端获取customers列表。但我无法在我的component中声明customersarray

我有像这个的客户界面

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

这里怎么了?

customers$的类型是Observable,因此不能为其分配空数组。因此根本不需要定义它。这就足够了->

customers$!: Observable<Customer[]>;

如果tsconfig.json中的"strictPropertyInitialization"设置为true,则添加此!,否则可以省略它。如果不立即初始化属性,则需要此!。您可以将"strictPropertyInitialization"设置为false,然后省略!。您可以查看属性'';没有初始值设定项,并且在构造函数中没有明确指定

此外,当您需要从某些东西创建Observable时,可以使用ofRxJS运算符将参数转换为可观察序列。https://rxjs.dev/api/index/function/of

一个添加是在.get之后添加casting,以便更清楚地了解类型。

getCustomers(): Observable<Customer[]> {
return this._http.get<Customer[]>(ApiConstants.getCustomers);
}

这个问题的答案可能会帮助你编写Typescript:类型X在类型Y length、pop、push、concat和26中缺少以下属性。[2740]

相关内容

最新更新