Fah*_*ari 6 http typescript angular
我想customers
通过调用从后端获取列表get
Http
。但我无法在我array
的.customers
component
我有这样的 customer.interface.ts
export interface Customer {
_id?: string,
name: string,
email: string,
phone?: string,
address?: string,
age?: number
}
Run Code Online (Sandbox Code Playgroud)
我有 http.service.ts
get = (url: string): Observable<any> => {
return this.http.get(this.createUrl(url), { headers: this.getHeaders() });
}
Run Code Online (Sandbox Code Playgroud)
在我的 customer.service.ts 中
getCustomers(): Observable<Customer[]>{
return this._http.get(ApiConstants.getCustomers);
}
Run Code Online (Sandbox Code Playgroud)
在我的 customer.component.ts 中
customers$: Observable<Customer[]> = [];
ngOnInit(){
this.customers$ = this.customerService.getCustomers();
}
Run Code Online (Sandbox Code Playgroud)
customers$: Observable<Customer[]> = []
现在,它在编译时在编辑器内部给了我这样的错误。
Type 'never[]' is missing the following properties from type 'Observable<Customer[]>': isScalar, source, operator, lif and 5 more
Run Code Online (Sandbox Code Playgroud)
这是怎么回事?
Cha*_*a15 10
的类型customers$
是 an Observable
,因此您不能为其分配空数组。所以你根本不需要定义它。这样就足够了 ->
customers$!: Observable<Customer[]>;
Run Code Online (Sandbox Code Playgroud)
!
如果您的"strictPropertyInitialization"
intsconfig.json
设置为,则添加此项true
,否则可以省略它。!
当您不立即初始化属性时,需要这样做。您可以设置"strictPropertyInitialization"
为false
然后省略!
。您可以看一下Property '...' 没有初始值设定项,并且在构造函数中未明确分配
另外,当您需要创建一个Observable
东西时,您可以使用of
RxJS 运算符将参数转换为可观察的序列。https://rxjs.dev/api/index/function/of
一项补充是在之后添加铸造,.get
以便更清楚地了解类型。
getCustomers(): Observable<Customer[]> {
return this._http.get<Customer[]>(ApiConstants.getCustomers);
}
Run Code Online (Sandbox Code Playgroud)
这个问题的答案可能对您有所帮助Typescript:类型 X 缺少类型 Y 长度、弹出、推送、连接等 26 个属性的以下属性。[2740] [2740]