5

I want to fetch customers list from my back-end via get Http call. But i am unable to declare array of customers in my component.

I have customer.interface.ts like this

export interface Customer {
  _id?: string,
  name: string,
  email: string,
  phone?: string,
  address?: string,
  age?: number
}

I have http.service.ts

get = (url: string): Observable<any> => {
 return this.http.get(this.createUrl(url), { headers: this.getHeaders() });
} 

In my customer.service.ts

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

In my customer.component.ts

customers$: Observable<Customer[]> = [];

ngOnInit(){
  this.customers$ = this.customerService.getCustomers();
}

Now it's giving me an error on this line customers$: Observable<Customer[]> = [] like this inside editor at compile time.

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

What's wrong here?

Fahad Subzwari
  • 2,109
  • 3
  • 24
  • 52

1 Answers1

10

Type of customers$ is an Observable, so you can't assign an empty array to it. So you don't need to define it at all. This would be enough ->

customers$!: Observable<Customer[]>;

Add this ! if your "strictPropertyInitialization" in tsconfig.json is set to true, if not you can omit it. This ! is needed when you don't initialize the property straight away. You can set "strictPropertyInitialization" to false and then omit the !. You can take a look at Property '...' has no initializer and is not definitely assigned in the constructor

Also, when you need to create an Observable out of something you can use of RxJS operator that converts the arguments to an observable sequence. https://rxjs.dev/api/index/function/of

One addition would be to add casting after .get to be more clear about the type.

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

Answer of this question may help you Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]

Chaka15
  • 1,105
  • 1
  • 8
  • 24