Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

RxJS from() and arrays

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[]>?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading