Home > database >  RxJS from() and arrays
RxJS from() and arrays

Time:09-28

I am trying to mock some data which will be displayed in an angular form.

I have a service which returns an Observable of type myObject[], I had tried to mock the data by hardcoding an array of this type and using from to create the observable. eg.

private getMockMyObjects(): MyObject[] {
  const myObjects: MyObject[] = [{
    name: 'AB',
    code: '123'
  },{
    name: 'CD',
    code: '456'
  }];
  return myObjects;
}

public getMyObjects(): Observable<MyObject[]> {
  const result = this.getMockMyObjects()
  return from(result);
}

However I get the error Type 'Observable<MyObject>' is not assignable to type 'Observable<MyObject[]>', why does from(result) create an Observable<MyObject> rather than Observable<MyObject[]>?

CodePudding user response:

from takes an iterable and converts it to an observable, which will emit all objects contained in this iterable in order (see https://rxjs.dev/api/index/function/from). If you want to create an observable which will emit one single array, you should use the of operator instead (see https://rxjs.dev/api/index/function/of). This will only emit the single value you passed to it and then complete the observable.

  • Related