0
votes

I'm using an Observable to return an object from service, that service checks if its item exist in cache otherwise it calls an http request and return the http's Observable, in case the item exist in cache i'm using rxjs from.

foo.service.ts:

private foos: FooModelDTO[] = [];
getFoo(id: string) : Observable<FooModelDTO> {
    var foo = this.foos.find(x => x.id === id);
    if (foo) {
        return from(foo);    --> error!        
    }            

    return this._foosAPIService.getFooById(id);
}

foo-api.service.ts:

getFooById(id: string) : Observable<FooModelDTO> {
    return this._httpClient.get<FooModelDTO>(
        this._configService.resourceApiURI + 'foos/' + id
    );
}

foo.model.ts:

export class FooModelDTO {
  public id: string;

  constructor (
    id: string
  ) 
  {
    this.id = id;
    // other properties...
  }
}

error TS2322: Type 'Observable<{}>' is not assignable to type 'Observable'. Type '{}' is missing the following properties from type 'FooModelDTO': id, imagePath, updateDate, title, and 6 more.

How to overcome this error? and return the cache result immediately in case it exist.

2
You need to use of operator instead of using from.micronyks
are you sure you want to get foo from foos array based on the index, not on the id property inside the 'FooModelDTO' ?Durgesh Pal
Hey @DurgeshPal thanks, I've updated the question to use findShahar Shokrani

2 Answers

1
votes

Update

The problem is u access your array with a string instead of a number. For that reason the type of foo is unknown instead of FooModelDTO.

Original answer

To answer your question we have to know what this.foods type is. If the typing is correct it should work. If you cannot fix its type, you can later cast foo.

var foo: FooModelDTO = this.foos[id] as FooModelDTO;
if (foo) {
    return from(foo);
}    

Also from needs an input of type ObservableInput<any>. I would recommend to use defer. Since the Observable returned if you have a cache miss is lazy, its a good idea to make the Observable, you get on cache hit, also lazy.

return defer(() => of(foo));
1
votes

I think the issue is in the Observable you are using.
from is used to turn an array, promise, or iterable into an observable.

You should use of instead of from.

import { of } from 'rxjs';

private foos: FooModelDTO[] = [];
getFoo(id: string) : Observable<FooModelDTO> {
    const foo = this.foos.find(x => x.id === id);
    if (foo) {
        return of(foo);       
    }            

    return this._foosAPIService.getFooById(id);
}