When authentication is successfully completed, proceed to the designated URL

Currently in the process of developing a project for educational purposes, utilizing Angular16 and Supabase as the backend technology. I have successfully implemented user sign-ins with Github, Google, and email (the method used for signing in doesn't affect the issue since it persists across all providers).

The problem at hand is as follows, I will provide the code snippet and then elaborate:

login.component.ts:

async signInWithGithub(): Promise<void> {
    try {
      this.loading = true;
      this.supabase.signInWithGithub()
      .then(() => {
        this.router.navigate(['login']);
      })
      .catch((error) => {
        if (error instanceof Error) {
          alert(error.message);
        }
      })
      .finally(() => {
        this.loading = false;
      });
    } catch (error) {
      if (error instanceof Error) {
        alert(error.message);
      }
    } finally {
      this.loading = false;
    }
  }

This code is intended to navigate once the authentication process is successfully completed. However, what actually occurs is that the navigation happens prematurely, and then after some time, the authentication finishes and redirects back to the login component.

Hence my query: How can I ensure the navigation only takes place upon completion of authentication?

All the pertinent code has been provided, although Supabase handles most of the functionality.

supabase.service.ts:

signInWithGithub(): Promise<OAuthResponse>{
    return this.supabase.auth.signInWithOAuth({ provider: 'github' });
  }

The primary method signInWithOauth() also delivers a Promise<OAuthResponse>.

EDIT: When signing in with Github (or any other provider), certain query parameters are appended to the URL followed by a page refresh.

Answer №1

When you sign in with a third party, the process involves redirecting to their website for authentication, which cannot be handled directly using Angular code. To manage the redirection, use the .signInWithOAuth method, which includes an options property containing a redirectTo property to redirect you back to a specific page on your web application.

this.supabase.auth.signInWithOAuth({ 
  provider: 'github', 
  options: { 
    redirectTo: 'http://example.com/login' 
  } 
})

Keep in mind that the redirectTo property requires a full URL. For detailed information, refer to the documentation.

Answer №2

Give this a try:

async githubLogin(): Promise<void> {
try {
  this.loading = true;
  await this.supabase.auth.signInWithOAuth({ provider: 'github' });
  this.router.navigate(['login']);
} catch (error) {
  if (error instanceof Error) {
    alert(error.message);
  }
} finally {
  this.loading = false;
}
}

It seems like the nested promises might be causing an issue, so simplifying it could help resolve any complications.

githubLogin() -> Promise

signInWithOAuth() -> Also returns a promise

This is just a basic suggestion based on my understanding of promises and their behavior.

For more information on working with promises, you can refer to this tutorial: https://www.tutorialspoint.com/how-to-use-typescript-with-native-es6-promises#

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

Exploring Angular's wild comparison capabilities for strings within HTML documents

I have a question that may seem basic, but I am curious if it is possible to use wildcards in *ngIf comparisons. Consider the following code snippet: <ng-container *ngIf="test == 'teststring'"> </ng-container> I am wonder ...

Adjust the size of a map on an HTML page after it has

Currently, I am utilizing Angular 2 to create a simple webpage that includes a Google 'my map' displayed within a modal. <iframe id="map" class="center" src="https://www.google.com/maps/d/u/0/embed?mid=1uReFxtB4ZhFSwVtD8vQ7L3qKpetdMElh&ll ...

Incorporating a sidemenu into a DOM using Ionic2 and Angular2 Typescript

I am currently struggling to properly integrate the sidemenu from the app.ts file. app.html: <ion-menu [content]="content"></ion-menu> <ion-nav id="nav" [root]="rootPage" #content ></ion-nav> app.ts import {App, IonicApp,Page, ...

Hide the tab in React Native's bottom tab navigation when on the current screen within the navigator

Currently, I am delving into learning react native. My project consists of 4 screens, yet I only require 3 buttons on my tab navigator. The objective is to hide or eliminate the active screen's tab from being accessible. Specifically, when on the home ...

The functionality of Angular 2's AsyncPipe seems to be limited when working with an Observable

Encountering an Error: EXCEPTION: Unable to find a support object '[object Object]' in [files | async in Images@1:9] Here's the relevant part of the code snippet: <img *ngFor="#file of files | async" [src]="file.path"> Shown is the ...

What are the steps to deploy my maven project (using angular and springboot) on tomcat?

My web application is built using Angular 8 and Spring Boot, both running locally on separate localhost ports. The integration works smoothly in my local environment with the Angular client on localhost:4200 and the Spring Boot server on localhost:8080. H ...

Having trouble uploading SharePoint list item with attachment from Angular to ASP.NET Core Web API via NgModel

Recently, I successfully added a SharePoint list item with an attachment from Angular to ASP.NET Core Web API. This was achieved using FormControl in the Angular application. I found guidance on how to upload files from Angular to ASP.NET Core Web API at ...

When another page is refreshed, Angular routing redirects back to the home page

Within my application, there is a homepage that appears after the user logs in, along with some other pages. However, I've encountered an issue where when I navigate to one of these other pages and then refresh the page, it redirects me back to the ho ...

Angular material table

I'm having an issue with deleting a record from a table that I created using Angular Material- Even after successfully deleting a record, the view does not refresh. Here is the HTML code snippet - <ng-container matColumnDef="delete"> ...

Issues with execution of promise code in Angular 11 post then method not triggering

I am facing an issue with my TypeScript function where the code after the promise is not being executed. The function is supposed to set up a protected resource map but it seems like Chrome is skipping over this part of the code entirely. export functio ...

What is the best way to utilize a single npm module in multiple TypeScript files?

Question: I keep encountering the error message "error TS2451: Cannot redeclare block-scoped variable 'os'" when I try to import the same npm module in multiple TypeScript files and run the TypeScript compiler tsc. Here is an overview of my proj ...

Instead of using `await asyncCall()`, try using `(await asyncCall())[0]`

After examining the Typescript code below, I'm curious to understand the rationale behind assigning myArray with (await asyncRPCCall())[0] instead of simply using await asyncRPCCall(). Why is the result placed inside () and why return only the first e ...

What is the ternary operation syntax for setting the img src attribute in Angular 8?

My data includes a property called "photo" which can either have a file name or be empty. For instance, it could be "steve.jpg" or just an empty string if Steve does not have a photo. In React JSX, I know how to use a ternary operator with the "photo" va ...

Using Kendo PanelBarItem to incorporate a personalized component as a child element

I was looking to design a component with PanelBarItems in its template. However, I'm facing issues and it doesn't seem to be working. Any suggestions? Main Component: import { Component } from '@angular/core'; @Component({ selecto ...

Encountering a 405 Error While Trying to Detect Location in Angular 7

I encountered an error 405 (Method Not Allowed) when trying to detect the location. Service public fetchWeatherDataByCoordinates(coordinates: ICoordinates): void { console.log("problem here") this.selectedLocationId.next(this.currentCoordinates ...

Typescript (ionic) loading animation that keeps users engaged while waiting for the data to be loaded

I'm looking to include an animation on the screen while waiting for the projects to load. constructor( public platform: Platform, private network: NetworkService, public navContrl: NavController, public modalCtrl: Moda ...

Tips for sending a parameter to an onClick handler function in a component generated using array.map()

I've been developing a web application that allows users to store collections. There is a dashboard page where all the user's collections are displayed in a table format, with each row representing a collection and columns showing the collection ...

Mapping of real-time locations on a map

Currently working on a personal project that involves analyzing real-time data, I am curious about what tools or technologies I can utilize to display geo locations on a map instantly. My preference is to implement this in either React or Angular. To cla ...

Troubleshooting Node TypeScript with Visual Studio Code using webpack bundling

(In a similar context to this query, but more focused on VsCode) I am attempting to debug the AngularU starter kit with Visual Studio Code. However, it is combining the TypeScript output into one bundle.js along with a side bundle.js.map: ↳web ↳dis ...

Why is the *.ngsummary.json file used?

I recently discovered AOT and ngc. When I run ngc, I notice numerous *.ngsummary.json files appearing in the src folder alongside the *.ts files. Can someone please explain their purpose? ...