code in subscribe executing repeatedly when it sho

2019-08-19 02:21发布

UPDATE

Actually, it is getting caught in the subscriptions (according to logs). It gets caught in both loadDistances and the scrolling one...depending on whether a scroll initiated the look-up, or if its just loading.

UPDATE

After looking at the console output more closely, I realized the problem isn't with my loadDistances function - it is with the code that runs when you scroll down and load new items...it is running automatically. As a workaround for not being able to use ion-infinite-scroll on one page, I use this code:

let element = this.elRef.nativeElement.querySelector('.scroll-content');
element.addEventListener('scroll', (event) =>
{
    var element = event.target;
    if (element.scrollHeight - element.scrollTop === element.clientHeight)
    {

        if(this.distancey.nativeElement.style.display != 'none') {
            this.doInfiniteD();
        }

        ...

This code is repeating over and over again after I use "Set Location" to set the user's location, and then swipe back to the root page which has the list of distances displayed. Other than this scenario, the scrolling code never repeats like this on its own.


I have this code which loads distances from the database which has already been sorted by firebase functions code (which is below):

loadDistances() {
    //return new Promise((resolve, reject) => {
      let cacheKey = "distances"
      let arr = [];
      let mapped;
      console.log("IN LOADDISTANCES #$$$$$$$$$$$$$$$$$$$$$");


      console.log("IN geo get position #$$$$$$$5354554354$$$$$$$");


        this.distancelist = this.af.list('/distances/' + this.username, { query: {
          orderByChild: 'distance',
          limitToFirst: 10
        }});

        let x = 0;
        this.subscription6 = this.distancelist.subscribe(items => {


           console.log(JSON.stringify(items) + "      length - 1 load");

           console.log("BEGGINNING STARTATKEY4 WITH DISTANCE:    " + this.startAtKey4);


           items.forEach(item => {
             let storageRef = firebase.storage().ref().child('/settings/' + item.username + '/profilepicture.png');

              storageRef.getDownloadURL().then(url => {
                console.log(url + "in download url !!!!!!!!!!!!!!!!!!!!!!!!");
                item.picURL = url;
              }).catch((e) => {
                console.log("in caught url !!!!!!!$$$$$$$!!");
                item.picURL = 'assets/blankprof.png';
              });

             this.distances.push(item);

             if(x == items.length - 1) {
               this.startAtKey4 = items[x].distance;
             }

             x++;
           })
      })

  }

When my app loads everything works as expected, the code in the subscription happens once and loads the first 10 according to their distance from the user. The problem is, I have a "Set Location" button on another page, which executes the firebase functions code below:

exports.sortDistance = functions.https.onRequest((req, res) => {
  // Grab the text parameter.
    var array = req.query.text.split(':');
  // Push the new message into the Realtime Database using the Firebase Admin SDK.
  // Get a database reference to our posts
    var db = admin.database();
    var ref = db.ref("profiles/stylists");
    var promises = [];
    // Attach an asynchronous callback to read the data at our posts reference
    ref.on("value", function(snapshot) {
      //console.log(snapshot.val());
      var snap = snapshot.val();
      for(const user in snap) {
        promises.push(new Promise(function(resolve, reject) {
            var snapadd = snap[user].address;
            console.log(snapadd + " snap user address (((((((())))))))");
            if(snapadd != null || typeof snapadd != undefined) {
                    googleMapsClient.geocode({
                      address: snapadd
                    }).asPromise()
                        .then(response => { 
                          console.log(response.json.results[0].geometry.location.lat);


                          console.log("  +++   " + response.json.results[0].geometry.location.lat + ' ' + response.json.results[0].geometry.location.lng + ' ' + array[0] + ' ' + array[1]);


                          var distanceBetween = distance(response.json.results[0].geometry.location.lat, response.json.results[0].geometry.location.lng, array[0], array[1]);
                          console.log(distanceBetween + "      distance between spots");
                          var refList = db.ref("distances/"+array[2]);
                          console.log(snap[user].username + "    snap username");
                          refList.push({ 
                            username: snap[user].username,
                            distance: Math.round(distanceBetween * 100) / 100
                          })

                          resolve();
                        })
                        .catch(err => { console.log(err); reject(err);})
            }
            else {
                resolve();
            }   
        }).catch(err => console.log('error from catch   ' + err)));
        //console.log(typeof user + 'type of');

      }

      var p = Promise.all(promises);
      console.log(JSON.stringify(p) +     "     promises logged");

    }, function (errorObject) {
      console.log("The read failed: " + errorObject.code);
    });
});

I'm fairly certain everything is in order here. It sorts the users according to their distance and creates a list in the database that I can see...and it only has 30 or so entries as it should (there are only 30 or so users in the database). However, after hitting the "Set Location" button and navigating back to the page with loadDistances (the root page)...it takes a few seconds to get back to it...and then it loads hundreds of entries...in seemingly random order, just repeating what I have in the list in the database, and it is loading them out of order as well...not sorted (not that I want the extra entries to be loading at all).

I can see in the console output for loadDistances() that the subscription code is being run over and over again after using the "Set Location". The console output for loadDistances() is at https://pastebin.com/zMZcj9wa.

Why is my code repeating inside the subscription? Does it have something to do with being subscribed while the "Set Locations" sorting happens in the firebase functions code?

0条回答
登录 后发表回答