1
votes

I am trying to cache some static data in my Angular CLI application I am building using rxjs.

I have followed this tutorial : https://blog.thoughtram.io/angular/2018/03/05/advanced-caching-with-rxjs.html

My setup:

  • Angular Cli Version : 6.0.8
  • Angular Core Version : 5.2.11
  • rxjs Version : 5.5.11

But I get this weird error in ng serve:

error TS2322: Type '() => Observable<StrategyI[]>' is not assignable to type 'Observable<StrategyI[]>'. Property '_isScalar' is missing in type '() => Observable<StrategyI[]>'.

And the following error in my google chrome console:

*strategy.html:60 ERROR Error: InvalidPipeArgument: 'function () {
        if (!this.cacheStrategies) {
            console.log("Strategies Cache Empty - reloading");
            this.cacheStrategies = this.getStrategies().pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__["shareReplay"])(CACHE_SIZE));
        }
        return this.cacheStrategies;
    }' for pipe 'AsyncPipe'
    at invalidPipeArgumentError (common.js:4283)
    at AsyncPipe.push../node_modules/@angular/common/esm5/common.js.AsyncPipe._selectStrategy (common.js:5732)
    at AsyncPipe.push../node_modules/@angular/common/esm5/common.js.AsyncPipe._subscribe (common.js:5714)
    at AsyncPipe.push../node_modules/@angular/common/esm5/common.js.AsyncPipe.transform (common.js:5688)
    at Object.eval [as updateDirectives] (GuidedTradeComponent.html:61)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:14697)
    at checkAndUpdateView (core.js:13844)
    at callViewAction (core.js:14195)
    at execEmbeddedViewsAction (core.js:14153)
    at checkAndUpdateView (core.js:13845)*

This is what I have in the dataservice.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { map, shareReplay } from 'rxjs/operators';

const CACHE_SIZE = 1;

@Injectable()
export class DataService {

  constructor(private http:HttpClient) {}

  private cacheStrategies: Observable<Array<StrategyI>>;

  private getStrategies() {
      return this.http.get<StrategyResponse>('api.mywebservice.com/strategy').pipe(
        map(response => response.value)
      );
  }

  getStrategiesO() {
    if (!this.cacheStrategies) {
      console.log("Strategies Cache Empty - reloading");
      this.cacheStrategies = this.getStrategies().pipe(
        shareReplay(CACHE_SIZE)
      );
    }
    return this.cacheStrategies;
  }

}

export interface StrategyI {
  stratId: number;
  stratName: string;
  stratDesc: string;
  stratBe? : string;           
  stratAlsoKnownAs? : string;  
  stratMoreInfoUrl? : string;
}

export interface StrategyResponse {
  type: string;
  value: Array<StrategyI>;
} 

This is what I have in strategy.component.ts

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { DataService, StrategyI } from '../../services/data.service';

@Component({
  selector: 'strategy',
  templateUrl: './strategy.html',
  styleUrls: ['./strategy.css']
})

export class StrategyComponent implements  OnInit {

  strategies: Observable<Array<StrategyI>>;

    constructor( private dataService: DataService )

  ngOnInit() {
    this.strategies = this.dataService.getStrategiesO;     <--- line with ERROR
  }
}

Finally, this is what I have for strategy.component.html

  <select id="Strategy" formControlName="Strategy" >  
    <option value="0">--Select--</option>  
    <option *ngFor="let strategy of strategies | async" value={{strategy.stratId}}>{{strategy.stratName}}</option>  
  </select> 

I have also tried changing the line :

import { Observable } from 'rxjs/Observable';

to just:

import { Observable } from 'rxjs';

But nothing I am trying is getting it to work....

3

3 Answers

0
votes

getStrategiesO it's a function, call it, now you just try to copy this func in strategies

  ngOnInit() {
    this.strategies = this.dataService.getStrategiesO();
  }
0
votes

It seems like you have a typo there

ngOnInit() { this.strategies = this.dataService.getStrategiesO; <--- line with ERROR }

if should be:

ngOnInit() { this.strategies = this.dataService.getStrategiesO(); <--- the brackets }

I sincerely hope this is not the cause

0
votes

I got it to work so that the data is cached in Angular using Observable and rxjs

Dataservice.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { map, shareReplay } from 'rxjs/operators';

const CACHE_SIZE = 1;

@Injectable()
export class DataService {

  constructor(private http:HttpClient) {}

  private cacheStrategies: Observable<StrategyI[]>;     <---- changed this line

  private getStrategies() {
      return this.http.get<StrategyI[]>('http://api.optionstrac.com/strategy');
      //cast straight to Strategy interface array and removed the pipe and the map
  }

  get getStrategiesO() {             <---- was missing the get
    if (!this.cacheStrategies) {
      console.log("Strategies Cache Empty - reloading");
      this.cacheStrategies = this.getStrategies().pipe(
        shareReplay(CACHE_SIZE)
      );
    }
    else {
      console.log("Strategies loaded from Cache");
    }   
    return this.cacheStrategies;
  }

}

export interface StrategyI {
  stratId: number;
  stratName: string;
  stratDesc: string;
  stratBe? : string;           
  stratAlsoKnownAs? : string;  
  stratMoreInfoUrl? : string;
}
// no longer needed strategyresponse interface

in strategy.component.ts

//strategies: Observable<Array<StrategyI>>;
strategies: Observable<StrategyI[]>;      <--- had to keep as Observable, but got rid of array

ngOnInit() {
  this.strategies = this.dataService.getStrategiesO;
}