Exploring Angular 10: Managing Two Promises in ngOnInit

I am currently working on integrating the Strava API into my Angular app.

To summarize briefly:

  1. When a user clicks on a button to connect to Strava
  2. They are redirected to Strava for authentication (using PKCE)
  3. Strava then redirects back to my app with a code
  4. In the ngOnInit function, I check for route parameters and if I have the code, I initiate two chained promises: the first one to get the Access Token from Strava and then save it into a Firebase database.

The issue I am facing is that sometimes the data is saved in Firebase and sometimes it is not. The behavior is inconsistent. What's strange is that I always go into my postNewToken function because it logs to the console.

  • If I only save to Firebase (without requesting a Strava token) in ngOnInit(), it works 100% of the time.
  • If I have a button that triggers the token request and data saving process, it seems to work every time.

I'm at a loss on how to resolve this. It appears to be more about properly chaining promises in ngOnInit but I'm unsure of how to address it.

The code from my component:

  ngOnInit() {
        const stravaCode = this.route.snapshot.queryParamMap.get('code');
        if (stravaCode !== undefined) {
          this.stravaService.handleStravaAuthorizationCode(stravaCode);
}

And in the associated service:

 // Handling received Strava Code
 handleStravaAuthorizationCode(authorizationCode: string) {
     this.getStravaToken(authorizationCode).then(res => {
       this.postNewToken(res).then(res => {
         this.router.navigate(['encoding']);
       });
     });
 }

 // Getting Strava access token for making API requests -> done only once
 getStravaToken(authorizationCode: string){
   if (authorizationCode !== undefined){
     console.log('Authorization code: ' + authorizationCode);

     const data = {
       client_id: environment.strava.client_id,
       client_secret: environment.strava.client_secret,
       code: authorizationCode,
       grant_type: 'authorization_code'
     };

     return this.http.post<StravaToken>(this.stravaTokenURL, data)
     .pipe(catchError(this.errorService.handleHttpError)).toPromise();
   }
 }

 postNewToken(stravaToken: StravaToken) {
   if (this.authService.isLoggedIn) {
       console.log('Saving Strava token into Firebase');
       console.log(stravaToken);
       return this.afs.collection('strava_tokens')
       .add(stravaToken).then(res => console.log(res), err => console.log(err));
   } else {
       return Promise.reject(new Error('No User Logged In!'));
   }
 }

Answer №1

At last, the realization struck me. It dawned on me that I was neglecting to wait for the firebase connection to be established. As a result, I couldn't add any new data due to lack of authentication.

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

Using 'require' within a nested directive that relies on the parent directive in AngularJS

Implementing a sub directive to be utilized in multiple directives is my current challenge. These parent directives share a common controller that has useful methods for updating scope variables within these directives: (potentially changing controllers ...

Adding child arrays to a parent array in Angular 8 using push method

Upon filtering the data, the response obtained inside the findChildrens function is as follows: My expectation now is that if the object length of this.newRegion is greater than 1, then merge the children of the second object into the parent object's ...

Angular Material's floating label feature disrupts the form field's outline styling

Whenever I try to change the appearance of the form field to outline, the floating label ends up breaking the outline. Here is a code snippet for reference: <mat-form-field appearance="outline"> <mat-label>Password&l ...

Struggling with integrating Bootstrap 4 Modals in Angular 2 environment

I attempted to incorporate a modal from into my navbar, but nothing happens when I click on it. <div class="pos-f-t fixed-top header"> <nav class="navbar navbar-inverse bg-inverse navbar-toggleable-md"> <button class="navbar- ...

Triggering animation with jQuery and CSS

I am working on a one-page site and I want to make a parallelogram disappear when a button is clicked for the next part. Currently, it is disappearing from right to left but I would like to change the direction to left to right. Additionally, I have a simi ...

AJAX loading footer content before images are fully loaded

I am a beginner when it comes to ajax and I'm facing an issue where the footer loads before the images, causing the images to overlap the footer. The problem is illustrated in the image below. <!doctype html> <html lang="en"> <head ...

What is the best way to save the output of an asynchronous function into a class attribute?

Currently, I am attempting to retrieve HTML content from a webpage by utilizing a class equipped with a single asynchronous method. This process involves Typescript 3.4.3 and request-promise 4.2.4. import * as rp from 'request-promise'; class H ...

Adding and adjusting the size of different DIV elements within a shared area

Looking to create a dynamic bar with the ability to add multiple child DIVs (similar to this: https://i.stack.imgur.com/tdWsq.jpg). Utilizing jQuery, jQuery UI, Bootstrap, and various plugins. The structure for the div (or span) system could be structured ...

Circular Dependency Detected in Angular 7 Library: A Tight Web of Directive, Service, and Module Interconnections

After setting up a new Angular 7 project with a library that includes a directive, a service, and a module (where the directive gets the service injected and the service has an injectionToken exported in the module), I encountered these warnings during com ...

Updating the DOM through Long Polling allows us to maintain existing attributes in jQuery Plugin

UPDATE: The functionality is all set; the pushes are working. The only issue I'm facing is that each push resets the #load_info div to empty. Is there a way to retain the original content inside the div, even though the content will be an updated vers ...

Verify the value of the variable matches the key of the JavaScript object array and retrieve the corresponding value

array = { event: [{ key: "value", lbl: "value" }], event1: [{ key: "value", lbl: "value" }] var variable; if(variable in array){ //need to handle this case } I am looking for a function that takes the name of an ar ...

How to convert an array of keys and an array of values into an array of objects using JavaScript

My question is similar to the one found here: Merging keys array and values array into an object using JavaScript However, I am unable to find a solution for my specific scenario. If I have these two arrays: const keys = ['x', 'y', &ap ...

Managing data flow in React and Reflux: Utilizing a single component duplicated in the DOM

Imagine this Tree scenario: <Homepage> <HeaderSection> <Navbar> <ShoppingCartComponent> </Navbar> </HeaderSection> <MainContent> <ShoppingCartComponent> &l ...

Differences between JavaScript's window.onload and body.onload functionsWhen

My inquiry is similar yet slightly distinct from the one queried here: window.onload vs <body onload=""/> The comparison in that prior query was between utilizing window.onload and inline js. My question pertains to the disparity between ...

What is the best way to insert a newline in a shell_exec command in PHP

I need assistance with executing a node.js file using PHP. My goal is to achieve the following in PHP: C:proj> node main.js text="This is some text. >> some more text in next line" This is my PHP script: shell_exec('node C:\pr ...

The jQuery $.change function is not functioning properly when used with a cloned select element

In my table, there is a button that allows you to add a new row by cloning the last one. Each row contains a <select> with a different name (0-9), all having the class .variable_priority. When clicking the button, the row clones successfully and the ...

What is the method to invoke a function within a factory in angularjs by using a string parameter?

I have a complex logic that I want to encapsulate in an AngularJS factory for easy use with dependency injection. The challenge is that the logic is dynamic, so I don't know in advance what functions will be available. What I have is a string represen ...

Tips for preventing the need to create a function within a loop

Currently, I am in the process of collecting data through REST calls. I have created a function that accesses a "directory" endpoint to retrieve a list of individuals. While I can easily obtain details about their children, I need to make individual AP ...

Utilize an Angular HttpInterceptor to invoke a Promise

I have an angular HttpInterceptor and I am in need of invoking an encryption method that is defined as follows: private async encrypt(obj: any): Promise<string> { However, I am unsure of how to handle this within the HttpInterceptor: intercept(req ...

Can you provide a step-by-step guide on creating a JSONP Ajax request using only vanilla

// Performing an ajax request in jQuery $.ajax( { url : '', data: {}, dataType:'jsonp', jsonpCallback: 'callbackName', type: 'post' ,success:function (data) { console.log('ok'); }, ...