Ionic2 update view whenever changes frequently in service


#1

I have written the code in service to get stock values from Light streamer. In my service I can see the changes from LS. It is changing frequently. But I couldn’t update this changes in my view file. I have written service as like below

export class MarketService{
    private stockChanged = new Subject<any>(); 
    itemNames = ["SPOT-GOLD", "CSILVER-2", "SPOT-INR", "MGOLD-1", "MSILVER-1"];
    fieldNames = ["desc", "bid", "ask", "high", "low", "ltp"];
    stocks: string[][];
    constructor(){
        this.initStocks();
        this.subscribeStocks();
    }
    initStocks() {
        // initialize stock matrix
    }

    subscribeStocks() {
        this.subscription.addListener({
            onItemUpdate: (updateObject) => {
                var itemName = updateObject.getItemName();
                updateObject.forEachChangedField((fieldName, fieldPos, val) => {
                      var itemIndex = this.itemNames.indexOf(itemName);
                      var fieldIndex = this.fieldNames.indexOf(fieldName);
                         this.stocks[itemName][fieldName] = val;
                         this.stockChanged.next(this.stocks);
                });
            }
        });
        this.lsClient.subscribe(this.subscription);
    }
    getCurrentRates(): Observable<any> {
      return this.stockChanged.asObservable();
    }

And in my component:

stockdata: any = {};
    subscription: Subscription;
    constructor(private stockService: MarketService) {
        this.subscription = this.stockService.getCurrentRates().subscribe(data => {  console.log(data);this.stockdata = data; });
    }
    ngOnDestroy() {
    this.subscription.unsubscribe();
  }

But not getting update in my component and view. But my service getting update frequently. Could you please help any one.


#2

so, the data changed… but there is nothing USING the data.
==> stockdata: any = {};

nothing references the stockdata variable


#3

Out of curiosity, what happens if you use something like lodash’s clonedeep to ensure that every time you call stockChanged.next() it is fed a brand-new object?

declare function require(mn: string): any;
let clonedeep = require('lodash.clonedeep');
...
this.stockChanged.next(clonedeep(this.stocks));

I suspect that since the component is seeing the same object over and over again, Angular’s change detector thinks nothing has changed.


#4

that won’t help as the service puts the data in this.stockdata, NOT this.stocks