Howto create a dataservice which i can subscribe to (observable)

I’m new to Ionic 2 and it’s observables. I have the following problem. I have a dataservice which has a function findAll. This function checks if the private var products != false if so it needs to return that value. if not, it needs to check the nativestorage and return that value if it is filled, if not, it checks http get and returns that

My problem, I wan’t to subscribe to the findAll function, in case of the http get this is possible, because it returns an observable (if i’m right), the nativestorage getitem returns a promise not an observable. and the first scenario of the already filled private variable is also not an observable.

Hopefully I described this problem clear enough

@Injectable()
export class dataService {
    products = false;

    constructor (http:Http) {
        this.http = http;
    } 

    findAll() {
        if (this.products !== false) {
            //HOWTO return this.products AS OBSERVABLE?
        } else {

            //HOWTO check native storage and return observable??
            NativeStorage.getItem('products') 

            //ELSE RETURN observable http get and 
            //HOWTO ADD TO this.products and NativeStorage.setItem
            return this.http.get(productsURL)
                .map(res => res.json())
                .catch(this.handleError);
        }

    }
}

Look at the documentation for Observable.of and fromPromise.

1 Like

and please type your functions and return values:

interface Product {
  id: number;
  name: string;
}
...
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of'
...
@Injectable()
export class dataService {
  products: Product[] = [];

  constructor (http:Http) {
        this.http = http;
    } 

    findAll(): Observable<Product[]> {
        if (this.products.length) {
          return Observable.of(this.products);
        }

        return this.http.get(productsURL)
          .map(res => res.json())
          .catch(this.handleError);
        };
    }
}

to add special methods or operators to your Observable you need to import them.

Ok thnk you. My only question left, is how to get the item from NativeStorage in the correct observable type. Becasue when I use fromPromise, it says that it’s not assignable to Observable<Products[]> (the fromPromise returns Observable<{}>

same error for the http.get

yeah then you have to change the functions type to Promise<Product[]>, but you need to change all Observables to Promises with .toPromise()

but then I can’t subscribe/ right?

yeah promises = then-ables so you would do that:

myCoolService.doSomething().then(() => {
  // success
}, () => {
  // error
})

If you are sending http-requests there is not really much a different. Only you can unsubscribe with observables to not get the result of pending requests.