Is there a way to navigate directly to a specific component without passing through the main component?

I'm currently utilizing the nativescript-urlhandler plugin in my Nativescript application. However, when I implement a router, the application routing first directs to the Main Component and then to the specific component I intend to reach.

My goal is to route directly to the desired component.

Below is the code from my routing.ts file:

const routes: Routes = [
  {
    path: 'home',
    component: HomeComponent,
    canActivate: [AuthGuard],
    children: [
      {
        path: 'fp', component: FirstPageComponent
      },
      {
        path: 'profile', component: ProfileComponent
      }
    ]
  },
  {
    path: 'outsidelogin',
    component: outsideloginComponent,
    children: [
      { path: 'login', component: LoginFirstComponent },
      { path: 'register', component: RegisterComponent },
      { path: 'resetPasswordRequest/:id', component: ResetPassIdComponent }
    ]
  },

    { path: '', redirectTo: '/home/fp', pathMatch: 'full' }
];

AuthGuard

 canActivate(): boolean {
        if (this.auth.isAuthenticated()) {
            return true;
        }
        this.router.navigate(['/outsidelogin/login']);
        return false;
    }

The issue lies within the following code:

ngOnInit() {
        if (this.auth.isAuthenticated()) {
            return true;
        }
        handleOpenURL((appURL: AppURL) => {
            console.log('Got the following appURL', appURL);
            this.myappurl = appURL
            let url_1 = this.myappurl.toString();
            let url_id = url_1.split("/").reverse()[0];
            this.resetpasss = url_id
            this.router.navigateByUrl('/outsidelogin/resetPasswordRequest/' + this.resetpasss);
        });
    }

Answer №1

Utilize Router Guards by implementing the canActivate method for your primary component route. If there's a URL triggered from handleOpenURL, deny the activation and steer towards the new URL.

Additional Note: Upon reviewing your code, it appears that optimizing your ResetPassIdComponent is crucial. Since it's nested within multiple page router outlets, consider relocating the component to the root level for enhanced performance and quicker initialization.

Insert the provided code snippet into your auth.guard.ts file and eliminate the URL handling logic from the app component.

import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { LoginService } from '~/services/login';
import { handleOpenURL, AppURL } from 'nativescript-urlhandler';

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private router: Router, private auth: LoginService) { }

    canActivate(): boolean {
        if (this.auth.isAuthenticated()) {
            return true;
        }

        const timeOut = setTimeout(() => {
            handleOpenURL(null);
            this.router.navigate(['/test/login']);
        }, 100);
        handleOpenURL((appURL: AppURL) => {
            if (timeOut) {
                clearTimeout(timeOut);
                console.log('Got the following appURL', appURL);
                let url_1 = appURL.toString();
                let url_id = url_1.split("/").reverse()[0];
                console.log(url_id);
                this.router.navigateByUrl('/test/questions/' + url_id);
            }
        });
        return false;
    }

}

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

Does the React memo function modify the component's prop type?

I've come across a strange issue where defining two components causes compilation errors when written separately but not when written in the same file. test3.tsx import React from "react"; type ValueType = number[] | string[] | number | st ...

Converting time from 00:00:01 to a format of 8 minutes and 49 seconds in Angular

Is there a way to transform a time value from 00:00:01 (not a date object) into a format showing 8 minutes and 49 seconds? Even after consulting the Angular 'date pipe' documentation, I couldn't find a solution to this issue. ...

Converting Typescript Object Types to Array Types with Tuple Structures

Presently, I have the following: interface Obj { foo: string, bar: number, baz: boolean } The desired outcome is to convert this interface into the tuple format below: [string, number, boolean] Is there a way to achieve this conversion? Up ...

Unable to classify mapRef.current

I am facing an issue with my react component that contains a leaflet map. TypeScript is warning me about line mapRef.current.setView(coords, 13), stating it is an "unsafe call of an any typed value" import 'leaflet/dist/leaflet.css'; import { Map ...

Error encountered while implementing onMutate function in React Query for Optimistic Updates

export const usePostApi = () => useMutation(['key'], (data: FormData) => api.postFilesImages({ requestBody: data })); Query Definition const { mutateAsync } = usePostApi(); const {data} = await mutateAsync(formData, { onMutate: ...

"Conceal Digits with SweetAlert2's Number Mask

Could you assist me in adding a number mask to an input field in sweetalert2? Here is my code: onClick(btn) { let code2_fa = ''; if (JSON.parse(localStorage.getItem('user')).password.two_factors.is_active) { swal({ ...

The information being sent from Angular is not being successfully transmitted to the XAM

Here is my Angular service post method: getUserDetails(username , password) { alert(password); return this.http.post<myData>("http://localhost/test/api/auth.php", { username, password }); } This is the structure of my PHP file: <?php ...

Exploring Angular's AG Grid ToolTips

I am encountering an issue while trying to implement AG Grids ToolTip functionality. Following the example provided at https://www.ag-grid.com/documentation/angular/component-tooltip/#example-custom-tooltip-component, I attempted to import { ITooltipAngula ...

Before the file upload process is finished, the progress of tracking Angular files reaches 100%

I am currently developing a service that is responsible for uploading a list of files to a backend server. createFiles(formData: any, userToken: string): Observable<any> { const headers = new HttpHeaders({'Authorization': 'Bearer ...

Cannot assign a string literal type in TypeScript to a type parameter that is extending a string literal type

Here is some code snippet that exhibits a specific issue: type FooType = 'Bar'; abstract class Meow<T extends FooType> { baz: T = 'Bar'; } An error is triggered stating Type '"Bar"' is not assignable to type 'T ...

Describing a property of an interface as the determined form of a conditional type that is generic

I am currently working on defining an interface that includes a method with a conditional function definition. For example: interface Example<T> { func: T extends string ? () => string : () => number; } class ExampleClass<T extends str ...

Angular service encounters NotYetImplemented error due to DOCUMENT injection token in SSR

I have a unique Angular SSR app with a special service that utilizes the document. I cleverly utilize the DOCUMENT injection token to provide this essential document for dependency injection. To take a peek at my innovative approach, check out my repo here ...

What is the best way to import a data type from another file into a `.d.ts` file without converting it into a module?

Recently encountered a peculiar scenario involving d.ts files and namespaces. I have some d.ts files where I define and merge a namespace called PROJECT. Take a look at how it's declared and automatically merged (across multiple files) below: file1 ...

Error: Attempting to access the 'subscribe' property of an undefined value (Observable)

In my TypeScript/Angular2/SPFx project, I have the following code snippet: // Populate the regulatory documents dropdown this.regulatoryDocumentsService.fetchRegulatoryDocumentsData().subscribe( data => { this.regulatoryDocumentsData = data }, ...

Setting up a development environment for .NET Core 2.0 with an Angular template and website template that can be easily downloaded using NPM

Currently, I am embarking on a new project utilizing .NET Core 2.0 with the Angular template. My intention is to integrate an existing HTML template into my project. After some research, I opted for a free HTML template called Gentelella which I have to in ...

Effective management and structuring of ExpressJS routes

I recently made the switch from PHP to NodeJS and Express, and I must say, it has been quite a learning experience. Following online tutorials to build web apps with Express has been eye-opening. I decided to tackle a project using just JavaScript, but I ...

What is the methodology for obtaining the setter property type in TypeScript?

Describe a scenario where an object contains both getter and setter methods with different types. How can we determine the type of the setter function? Consider defining an object with getter and setter functions like the example below: type Foo = { g ...

Discovering how to display the hidden messages section in the absence of any ongoing chats with the help of angular2

I currently have 2 tabs set up on my page. The active messages tab is functioning perfectly without any issues. However, I am encountering an error with the closed messages tab. If there are no messages in this tab, the system displays an error message w ...

What could be causing the code to not wait for the listener to finish its execution?

I've been attempting to make sure that the listener has processed all messages before proceeding with console.log("Done") using await, but it doesn't seem to be working. What could I possibly be overlooking? const f = async (leftPaneRow ...

Setting dynamic attributes on an Angular 2 component within an HTML template

Can anyone provide me with an example of how to set an attribute on a component based on a certain expression? This is what I have currently: <div [danger]="inArray(choice.likers, user, id)"></div> However, it appears that this code does not ...