Problems with onQueryEvent observable failing upon routing in Nativescript with Angular

127 Views Asked by At

I am using Nativescript with Angular and have code written that succesfully calls an onQueryEvent from the nativescript-firebase-plugin for data set upon first building the application. However after following a route to a second component containing the exact same onQueryEvent the data succeeds to retreive a complete list but skips the onQueryEvent.

In all honesty I don't know best practices for queries in any situation let alone this one, so I hope it is just a matter of manipulating how I call the onQueryEvent.

I believe the problem to be in the firebase.query inside the getMyTransactionList() function of the firebase.service.ts file.

the overview.component.html page has a transaction | async RadListView that successfully filters upon running tns run android. Then clicking any link directing to the deal-summary.component.html page where the function is re-iterated refuses to query by the static storage variable set in the firebase.service

Here is my code:

firebase.service.ts

export class FirebaseService {

private _allItems: Array<any> = [];
items: BehaviorSubject<Array<any>> = new BehaviorSubject([]);
public storage: any = '-KomUSGcX-j6qQmY4Wrh'; // set statically to test different routes

constructor(
            private ngZone: NgZone,
            ){}

// fetch data

  getMyDealList(): Observable<any> {
    return new Observable((observer: any) => {
      let path = `deals/${BackendService.token}`;

        let onValueEvent = (snapshot: any) => {
          this.ngZone.run(() => {
            let results = this.handleSnapshot(snapshot.value);
             observer.next(results);
          });
        };
        firebase.addValueEventListener(onValueEvent, `/${path}`);
    }).share();              
  }


    getMyTransactionList(): Observable<any> {
    return new Observable((observer: any) => {

      let path = `transactions/${BackendService.token}`;

      // this is a merge of jen loopers giftler code combined with nativescrip-firebase-plugins standard onQueryEvent.  It works on the first load but routing to a second instance of the same function retrieves all the data without queryEvent
    let onQueryEvent = (snapshot: any) => {
          this.ngZone.run(() => {
            let results = this.handleSnapshot(snapshot.value);
             observer.next(results);
          });
        };

      firebase.query(
        onQueryEvent,
        `/transactions/${BackendService.token}`,
        {

            singleEvent: true,

            orderBy: {
                type: firebase.QueryOrderByType.CHILD,
                value: 'dealId' // mandatory when type is 'child'
            },

            range: 
              {
                  type: firebase.QueryRangeType.EQUAL_TO,
                  value: `${this.storage}` // this calls a static variable for testing consistency
              }
            ,

        }
    );

        firebase.addValueEventListener(onQueryEvent, `/${path}`);
        console.log("transaction Listener added");
    }).share();              
  }



  handleSnapshot(data: any) {
    //empty array, then refill and filter
    this._allItems = [];
    if (data) {
      for (let id in data) {   
        let result = (<any>Object).assign({id: id}, data[id]);
          this._allItems.push(result);

      }
      this.publishUpdates();
    }
    return this._allItems;
  }


 publishUpdates() {
    // here, we sort must emit a *new* value (immutability!)
    this._allItems.sort(function(a, b){
        if(a.date < b.date) return -1;
        if(a.date > b.date) return 1;
      return 0;
    })
    this.items.next([...this._allItems]);
  }
}

app.component.ts

<page-router-outlet></page-router-outlet>

overview.component.ts

 export class OverviewComponent implements OnInit {

    public deals: Observable<any>;
    public transactions: Observable<any>;

    constructor(private router: Router, 
                private firebaseS: FirebaseService,
                ){  }

  ngOnInit() {
    this.deals = <any>this.firebaseS.getMyDealList();
    this.transactions = <any>this.firebaseS.getMyTransactionList();
  }


  viewDealSumm(id){
         this.router.navigate(['dashboard/deal-summary', id]);
    }
}

overview.component.html

          <RadListView [items]="deals | async ">
                <ng-template tkListItemTemplate let-item="item">
                    <StackLayout (tap)="viewDealSumm(item.id)">
                         <Label [text]="item.dealName"></Label>
                       </StackLayout>
                    </ng-template>
                </ListViewGridLayout>
            </RadListView>





            <RadListView [items]="transactions | async " >
                  <ng-template tkListItemTemplate let-item="item">
                       <GridLayout>
                            <Label [text]="item.transName"></Label>
                       </GridLayout>
                   </ng-template>
            </RadListView>

deal-summary.component.ts

export class DealSummaryComponent implements OnInit {

    public transactions: Observable<any>;

    constructor(
                private firebaseS: FirebaseService,
                         ){ }

  ngOnInit() {
    this.transactions = <any>this.firebaseS.getMyTransactionList();
  }

deal-summary.component.html

     <RadListView [items]="transactions | async " >
        <ng-template tkListItemTemplate let-item="item">
            <GridLayout >
                <Label col="1" [text]="item.transName"></Label>
            </GridLayout>
        </ng-template>
     </RadListView>
0

There are 0 best solutions below