Issue with Ionic 3 subscribes triggering repeatedly

I've been struggling with the code for an Ionic taxi app for a few weeks now. My main issue is that whenever the page loads, the subscription gets triggered multiple times along with other functions within it. The same problem occurs when any travel information is updated in Firebase.

Is there a way to load the travel and driver information just once so that the screen only monitors the other services?

Traveling.ts:

export class TravelingPage {

  driver;
  trip;
...

constructor(
        public nav: NavController,
        ...
      ) {
        ...
        if (this.navParams.get('tripId')) {
          this.tripId = this.navParams.get('tripId')
        }
        else {
          this.tripId = this.tripService.getId();
        }

      }

        ionViewDidLoad() {

        this.tripService.getTrip(this.tripId).take(1).subscribe(snapTrip => {
          this.driverService.getDriver(snapTrip.driverId).take(1).subscribe(snapDriver => {

              // load trip data
              this.trip = snapTrip;

              // load driver data
              this.driver = snapDriver;

              // watchTrip
              this.watchTrip(this.trip.id);

              // start map
              this.loadMap();

              // check if trip is already paid
              if (!this.trip['paymentData'] && this.orderStatus == false) {
                // pay Trip
                this.tripService.doOrder(this.trip);
              } else {
                console.info('Paid already. Do nothing');
              }
            }
          });
        })

      }
...
}

TripService.ts:

getTrip(id) {
    return this.db.object('trips/' + id);
  }

Answer №1

It's important to remember to unsubscribe from subscriptions when using them to avoid multiple subscriptions. One method is to assign the subscription to a variable and then unsubscribe from it in the ionViewWillLeave() lifecycle hook

Answer №2

Issue resolved! The problem was identified as a duplicate Firebase node status.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with triggering failure action after receiving a 500 error from DELETE api in ngrx

Whenever I make a delete API call from my Angular application using the correct parameters, everything works smoothly and the success action is triggered as expected. However, if there's a mistake in any of the parameters or the URL, I receive the app ...

What is the solution for fixing the Typescript error in formik onSubmit?

I encountered an error while using the onSubmit prop of Formik: The type '(values: { email: string; password: string; }) => { type: string; payload: { email: string | null; password: string | null; }; }' is not compatible with the type &apos ...

The file path and installed npm package intellisense does not appear in VS Code until I press Ctrl + space for TypeScript

Before pressing ctrl + space, intellisense shows: click here for image description After pressing ctrl + space, intellisense displays: click here for image description Upon updating to vs code version 1.11.0 and opening my project, I encountered an issu ...

Is there a way to utilize Angular in identifying whether a given value corresponds with the value of a particular radio button within my application?

I have an array of lists that I need to display in radio buttons. Like this: https://i.stack.imgur.com/cmYgO.png https://i.stack.imgur.com/Zx4bm.png https://i.stack.imgur.com/jBTe3.png My goal is to have a checkbox that matches the values loaded from a ...

A guide to merging two JSON objects into a single array

Contains two different JSON files - one regarding the English Premier League stats for 2015-16 season and the other for 2016-17. Here is a snippet of the data from each file: { "name": "English Premier League 2015/16", "rounds": [ { "name": ...

Using JQuery within Angular 4 is a valuable tool for enhancing the functionality

As a newcomer to Angular, I am experimenting with using jQuery alongside Angular 4. In my search for information, I stumbled upon this question on Stack Overflow. Inside the question, there was an example provided that can be found here. However, when att ...

A helpful guide on troubleshooting the ngx-bootstrap error within Angular-14

While working on my Angular-14 project, I encountered an issue with the package.json file: This is how my package.json looks like: "dependencies": { "@angular/animations": "^14.0.0", "@angular/common": "^14 ...

Preselecting items in PrimeNG Checkbox: A step-by-step guide

How can I ensure that the already selected item is displayed upon loading this div? The code in `rp` consists of an array of type Permission with one element, which should be automatically selected. What could be causing the issue? Here is the HTML snippe ...

One way to change the cursor CSS property is by dynamically altering it based on scrolling behavior. This involves modifying the cursor property when scrolling

I'm attempting to adjust the cursor property within an Angular function. The issue I'm facing is that when I begin scrolling the webpage, the cursor changes to a pointer, but when I stop scrolling, it remains as a pointer. I've attempted to ...

Troubleshooting Gitlab CI/CD freezing upon committing updates

Hey there, I'm running into an issue while setting up Gitlab CI/CD with the Angular ng test command. The pipeline starts as expected, but then it gets stuck. I understand that Karma relies on chrome. I seem to be missing something. Any advice would b ...

What sets apart element(by.id('username')) from browser.driver.findElement(by.id('username')) when utilizing protractor?

Can someone clarify the difference between: element(by.id('userId')).sendKeys('abc'); and browser.driver.findElement(by.id('userId')).sendKeys('abc'); when using Protractor? While working on UI tests for my Angu ...

What is the best way to add a hyperlink to a cell in an Angular Grid column

I need help creating a link for a column cell in my angular grid with a dynamic job id, like /jobs/3/job-maintenance/general. In this case, 3 is the job id. I have element.jobId available. How can I achieve this? Here is the code for the existing column: ...

What is the reason behind receiving the error message "Unable to resolve all parameters for ApplicationModule"?

I am experiencing an issue with my Angular app as it is not working properly in CodeSandbox. The error message I receive is: Can't resolve all parameters for ApplicationModule evaluate main.ts:11:25 8 | enableProdMode(); 9 | } 1 ...

Ways to activate auto completion without using a string

Can anyone assist us with the tinymce editor? We have implemented an auto completion feature using a plugin from TinyMCE's documentation, but we are having trouble changing the triggering behavior. Currently, it only suggests options when "@" is typed ...

Karma's connection was lost due to a lack of communication within 10000 milliseconds

The Karma test suite is encountering issues with the following message: Disconnected, because no message in 10000 ms. The tests are not running properly. "@angular/core": "7.1.3", "jasmine-core": "3.3.0", "karma-jasmine": "1.1.2", The failure seems t ...

Is there a way to prevent the leaderboard from resetting each time I restart my client?

Is it possible to prevent the leaderboard from resetting every time I restart my client? You can see an example here: https://i.stack.imgur.com/2nEPw.png Please disregard the "undefined" error, I will correct it. In the current setup, the leaderboard onl ...

Creating Custom Form Control with Custom Validation in Angular 6

I designed the app-input component for displaying an input textbox. I am struggling to implement custom form validation. Can you offer any suggestions? ...

What could be causing the failure to typecheck the sx prop?

Trying to implement sx prop-based styling in a React project. Looking to utilize the theme using a theme getter. While styles render correctly in the browser, TypeScript raises errors and understanding the type ancestry is proving challenging. Working e ...

Webpack: The command 'webpack' does not exist as a recognized cmdlet, function, script file, or executable program

Attempting to set up a new project using webpack and typescript, I have created the project along with the webpack file. Following the instructions on the webpack website, I successfully installed webpack using npm install webpack webpack-cli --save-dev ...

Restangular: The use of await causes execution to halt when requests fail

I encountered an error interceptor that looks like this: RestangularProvider.addErrorInterceptor((response) => { const error = EnumerableFromObject(response.error.Errors) .Select(i => i.Value.Message) .FirstOrDefault(); toastr.e ...