【问题标题】:type 'never[]' is missing the following properties from type 'Observable<Customer[]>'类型 'never[]' 缺少来自类型 'Observable<Customer[]>' 的以下属性
【发布时间】:2022-04-21 20:07:20
【问题描述】:

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

我有这样的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&lt;Customer[]&gt; = [] 上给了我一个错误,就像在编译时在编辑器中一样。

Type 'never[]' is missing the following properties from type 'Observable<Customer[]>': isScalar, source, operator, lif and 5 more

这里有什么问题?

【问题讨论】:

    标签: angular typescript http


    【解决方案1】:

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

    customers$!: Observable<Customer[]>;
    

    如果您在tsconfig.json 中的"strictPropertyInitialization" 设置为true,则添加此!,否则您可以省略它。当您不立即初始化属性时,需要此 !。您可以将"strictPropertyInitialization" 设置为false,然后省略!。你可以看看Property '...' has no initializer and is not definitely assigned in the constructor

    另外,当你需要创建一个Observable 时,你可以使用of RxJS 操作符将参数转换为一个可观察的序列。 https://rxjs.dev/api/index/function/of

    一个补充是在.get 之后添加转换以更清楚地了解类型。

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

    这个问题的答案可能对你有帮助Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-11
      • 2022-09-28
      • 2020-09-09
      • 2021-04-20
      • 2021-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多