I am having trouble with the routerExtensions.navigate function in my NativeScript app

I'm currently working on a simple NativeScript / Angular project that is based on the code sample located at:

https://github.com/alexziskind1/nativescript-oauth2/tree/master/demo-angular

This project allows users to log in with their Google credentials.

Once the user enters their login information, they should be redirected back to the app and taken to the route: /authenticated.

The issue I am facing lies within the file login.component.ts. When the method

this.routerExtensions.navigate(["/authenticated"])
is called, sometimes it successfully redirects the user to the specified route, but other times it does not. I've tried to analyze the circumstances of when this occurs, but it seems to happen randomly.

On the other hand, I want to mention that I am always able to see the access token logged in the console, indicating that the authService is functioning correctly. However, the problem seems to be with the navigation aspect.

Additionally, I am uncertain whether I should use:

this.routerExtensions.navigate(["/authenticated"])

or

this.routerExtensions.navigate(["../authenticated"])

In the official code sample, there are two dots (as shown in the second case) as seen here:

https://github.com/alexziskind1/nativescript-oauth2/blob/master/demo-angular/src/app/login/login.component.ts#L23

However, that doesn't appear to be the root cause of the issue.

I believe I may be overlooking something here.

Below you'll find snippets of my code.

...

Answer №1

If you're facing a similar situation, I believe going directly to authenticated is the right approach.

this.routerExtension.navigate('authenticated'], {
    clearHistory: true
});

After a successful login, it's advisable to clear the history as well.

You can also opt for

this.routerExtension.navigateByUrl('/authenticated')
if that suits your preference better.

In addition, consider adding some helpful tracing in your app-routing module:

NativeScriptRouterModule.forRoot(routes, {
    enableTracing: true
})

Furthermore, introducing a timeout before navigating might be beneficial, like so:

public onTapLogin() {
        this.authService
            .tnsOauthLogin("google")
            .then((result: ITnsOAuthTokenResult) => {
                console.log("back to login component with token " + result.accessToken);
                setTimeout( () => {
                    this.routerExtensions
                        .navigate(["/authenticated"])
                        .then(() => console.log("navigated to /authenticated"))
                        .catch(err => console.log("error navigating to /authenticated: " + err));
                }, 300);
            })
            .catch(e => console.log("Error: " + e));
    }

Usually, using a timeout is only necessary when navigating while a modal is open.

UPDATE: After testing your sample project, I didn't encounter any issues with navigation following Google sign-in. Given the random error you're experiencing, it could potentially be related to a UI timing issue. In such cases, utilizing setTimeout as my last suggestion should serve as an effective workaround.

Answer №2

When I encountered this problem on the Android Emulator, I found that updating Nativescript and changing the device being used in the emulator resolved it. I recommend trying these updates and adjustments to see if they help resolve your issue as well.

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

Transformed Vue code with TypeScript using a more aesthetically pleasing format, incorporating ref<number>(0)

Original Format: const activeIndex = ref<number>(0) Formatted Version: const activeIndex = ref < number > 0 Prettier Output: click here for image description Prettier Configuration: { "$schema": "https://json.schemastore.org ...

The attribute 'X' is not present in the 'context | null' type. Error code: ts(2339)

I'm totally puzzled by this issue. Even though I clearly defined the function type in TasksContextType, why is TypeScript throwing an error in my code... Error: Property 'addTask' does not exist on type 'TaskContextType | null'. t ...

Node Express and Typescript app are failing to execute new endpoints

Hello, I'm currently diving into Node express and working on a simple CRUD app for pets. So far, I've successfully created 2 endpoints that are functioning properly. However, whenever I try to add a new endpoint, Postman fails to recognize it, g ...

Tips for embedding different pages within a single page using Angular 5

My project consists of 4 pages. [ { path: 'page1', component: Page1Component }, { path: 'page2', component: Page2Component }, { path: 'page3', component: Page3Component }, { path: 'page4', component: Page4Co ...

Loading SVG templates dynamically in Angular can be done by utilizing a string

Is it possible to convert SVG content loaded from a server into a component template in Angular, with the ability to bind properties to it? For example, <tspan [attr.color]="textColor" ...>{{myText}}</tspan>. I have tried loading and ...

When Typecasted in Typescript, the result is consistently returned as "object"

Consider a scenario where there are two interfaces with identical members 'id' and 'name': export interface InterfaceA { id: number; name: string; //some other members } export interface InterfaceB { id: number; nam ...

Error message from Angular image-cropper indicating a Cross-Origin Resource Sharing (

I am facing an issue with my image cropper that uses the imageUrl. The code for the image cropper is as follows: <image-cropper (imageCropped)="imageCropped($event)" [aspectRatio]="600 / 450" [imageChangedEvent]="imageChan ...

Guide on extracting FormData from a POST request in Node.js using Multer

I have a specific challenge where I need to store formData on a mongodb schema, using nodejs and express for the backend, along with multer as middleware. This particular formData consists of both a string and a blob. My main issue is capturing and saving ...

Using jasmine spy object to replace injected Renderer in shallow tests for Angular 2 components

Angular Component File 'zippy.component.ts': import { Component } from '@angular/core'; import {ZippyService} from '../services/zippy.service' import {Renderer} from '@angular/core' @Component({ selector: ...

Array of objects not being shown in select dropdown

I have a component with a dropdown feature. Below is the code snippet from the component: export class MyComponent { MyObjectArray: MyObject[] = []; constructor(private _service: MyService) } ngOnInit() { this._service.get().do((response): MyObjec ...

How can I update a value using a specific key in Angular?

So, I have a string value that I need to pass to another function. For instance, if the string is 'eng', I want it to be converted to 'en'. I'm looking for a solution that does not involve using slice or if statements. I attempted ...

Angular 10: Manually include the (*)d.ts file in the compilation process

I am currently experiencing an issue with my Angular library that has description files *.d.ts in a specific structure as shown below: ├ src │ ├ my-lib │ │ ├ my-typedef.d.ts │ └ public_api.ts │ └ tsconfig.lib.json In the tsconfi ...

Leverage the Nuxeo client SDK with Angular 6 for seamless integration with RESTClient in

Looking to integrate the Nuxeo ClientSdk with my Angular 6 client to consume its REST API, but facing issues due to the lack of typescript definitions for this JavaScript package. Tried importing the library into my project using the following code snippe ...

Bring in modules from around the world into your Ionic framework built with Angular

While working with the ionic framework, I have noticed that many of my pages require the same modules. import { Http } from '@angular/http'; import { Storage } from '@ionic/storage'; Therefore, I find myself setting them in the constr ...

Steps for returning an observable from a service in Angular following a series of pipe operations

Currently, I am attempting to link/combine operations and produce an Observable from a Service in Angular that utilizes AngularFire. I have successfully implemented this with promises. Service saveDiploma(diploma: { title: any; description: any; picture ...

I'm curious about how to link a JSON field using dot notation in Angular 12 HTML

Does anyone know how to bind a JSON field using dot paths in Angular 12 HTML? For example: //Angular data: any = { name: 'x1', address: { city: 'xyz' } }; field: any = 'address.city'; //Html <input [(ngModel)]="data[ ...

Issue - The 'defaultValue' is failing to load the state value, and the 'value' is not being updated when changed

My current setup involves an input field in my MovieInput.tsx file: <input id="inputMovieTitle" type="text" onChange={ e => titleHandleChange(e) } value={ getTitle() }> </input> This is how the titleHandleChange function ...

Refining a Collection of Possible Options

If I have an array of type Maybe<int>[] and want to extract only the values that are not None, what is the most efficient approach while ensuring TypeScript recognizes the output as int[]? It seems like declaring the result type as int[] is the way ...

Sending a Typed useState Hook to a child component results in it being interpreted as undefined, even if the defaultState is not

This code snippet showcases my attempt at creating a form with the functionality to generate multiple entries of the same form upon a button click. The ultimate goal is to store the input data in an array of objects, where each object corresponds to one co ...

Angular Material's Material Button exhibits varying behavior when the text on the button is clicked

Let's analyze the code snippet below: HTML: <button mat-flat-button id="test" (click)="toggle($event)">Click me!</button> Component: toggle(event) { let id: string = (event.target as Element).id; console.log(id) console.log(event ...