Angular2 retrieve the current route object similar to ng-route's toState parameter

@RouteConfig([
{
    path: '/login',
    name: 'Login',
    component: LoginComponent
},
{
    path: '/search',
    name: 'Search',
    component: SearchComponent,
    needAuth: true
},
{
    path: '/result/:searchString',
    name: 'Result',
    component: ResultComponent,
    needAuth: true
},
{path: '/**', redirectTo: ['Login']}
])

I have defined a configuration like the one above. Now I am trying to figure out how to identify the current route object, specifically for routes that require authentication before access.

{
    path: '/result/:searchString',
    name: 'Result',
    component: ResultComponent,
    needAuth: true
}

My goal is to create functionality in my app where if a user is not logged in and the current route object has the needAuth property set to true, they will be redirected to the login page; otherwise, they should be directed to the search page.

After some research, I came across this solution:

        this._router.subscribe((url) => {
        this._router.recognize(url).then((instruction) => {
            if(this._authService.getUser() == null && instruction.component.routeData.data.needAuth) {
                this._router.navigate(['Login'])
            }

            if(this._authService.getUser() !=null && !instruction.component.routeData.data.needAuth) {
                this._router.navigate(['Search'])
            }
        });
    });

Answer №1

To enhance the functionality of the RouterOutlet class and intercept route activation on a global scale, consider extending it as follows:

import {Directive} from 'angular2/core';
import {Router, RouterOutlet, ComponentInstruction} from 'angular2/router';

@Directive({
  selector: 'router-outlet'
})

export class MyCustomRouterOutlet extends RouterOutlet {
  (...)

  activate(oldInstruction: ComponentInstruction) {
    var url = this.parentRouter.lastNavigationAttempt;
    console.log('Attempting to navigate');
    if (oldInstruction.routeData.needAuth && !this.authService.loggedIn){
      var newInstruction = new ComponentInstruction('Login', [], new RouteData(), Login, false, 1);
      return super.activate(newInstruction);
    } else {
      return super.activate(oldInstruction);
    }
  }
}

Remember to define your routes like this:

{
  path: '/result/:searchString',
  name: 'Result',
  component: ResultComponent,
  data: {
    needAuth: true
  }
}

For further information, refer to these resources:

Answer №2

Instead of using the property

needAuthorization: true

within the RouteConfig, opt for

data: {needAuthorization: true}

and then inject it as follows

constructor(private routeData: RouteData) {
  if(routeData.needAuthorization) {
    ...
  }
}

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

Utilizing the MapToIterable Angular Pipe with TypeScript

Exploring the implementation of a pipe in Angular. Discovered that ngFor doesn't work with maps, prompting further research to find a solution. It seems that future features may address this issue, but for now, utilizing a mapToIterable pipe is the re ...

Inspecting a union type with a TypeScript property validation

I have defined a union of two types in my code. Here are the definitions: type Generic = { subtype: undefined, user: string, text: string } type Other = { subtype:'message', text: string } type Message = Generic | Other; Within my co ...

Does the directive lack access to transcluded elements?

I seem to be missing something here, as I can't seem to get the desired outcome with my code: http://plnkr.co/edit/Qe2IzMMMR5BJZJpwkx9e?p=preview My goal is to create a directive that can be applied to a top-level <nav> element, and then manipu ...

Transferring documents from an angular ionic application to a slim php framework on the localhost

Hey there! I've got a project on my localhost where I need to upload files to a local folder. I'm sharing the code here in hopes that someone can assist me. HTML: <ion-item ion-item *ngFor="let item of lista" menuClose> Floor: ...

Guide on how to address the problem of the @tawk.to/tawk-messenger-react module's absence of TypeScript definitions

Is there a way to fix the issue of missing TypeScript definitions for the @tawk.to/tawk-messenger-react module? The module '@tawk.to/tawk-messenger-react' does not have a declaration file. 'c:/develop/eachblock/aquatrack/management-tool-app ...

md-autocomplete not displaying the item that was selected

I recently added an md-autocomplete feature to my Angular.js website. The search and selection functionality is working properly as it updates the displayed list accordingly. However, I am facing an issue where I can't seem to retrieve the selected it ...

flexanimate functioning only on the first attempt

I've been attempting to use jQuery and AngularJS to control the movement of a flex slider using keyboard input. However, I am finding that it only works once with FlexAnimate and then stops working. Can anyone offer insight as to why it is not functio ...

How can I store an array of objects in a Couchbase database for a specific item without compromising the existing data?

Here is an example: { id:1, name:john, role:[ {name:boss, type:xyz}, {name:waiter, type:abc} ] } I am looking to append an array of objects to the existing "role" field without losing any other data. The new data should be added as individual ob ...

Secure User Verification in Laravel 5 and AngularJs sans the need for JWT Tokens

I am currently working on a project that involves utilizing a Laravel-based back-end and a front-end built with both Laravel and AngularJS. After completing 40% of the back-end development, I am now faced with the task of implementing the front-end. Howev ...

Using the attribute data-ng-repeat along with the <option> tag allows for dynamic iteration and

Hello there, I am a beginner with AngularJS and I am struggling to understand how to create my <option> list. I would like my output to resemble the example in this fiddle: http://jsfiddle.net/XdpJv/ This is what my current code looks like: <se ...

Angular Mat AutoSuggest - Improving User Experience

I am encountering an issue where I can retrieve the list, but as soon as I input any of my data, I receive an error ERROR TypeError: Cannot read properties of null (reading 'valueChanges'). How can I resolve this? I have verified the name of my f ...

Harness the Power of Generics in TypeScript for Automatic Type Inference

function execute<T>(operation1: (input: T) => void, operation2: (input: { key: string }) => T): void {} execute((params) => {}, () => 23); // The params here can be correctly inferred as number execute((params) => {}, (arg) => 23) ...

Unlock the power of deep linking with the Branch SDK and integrate seamlessly with

Trying to utilize Branch's deep-linking features, particularly deferred deep-linking, in my Ionic project has been a challenge. The issue lies in the incomplete documentation provided for Cordova/Ionic integration by Branch. Despite installing their C ...

Whenever attempting to execute a protractor test using cucumber, a specific error message is displayed reading: "E/launcher - Process exited with error code 1"

Looking for some assistance. I seem to be stuck and can't pinpoint the issue. Package.json { "devDependencies": { "@cucumber/cucumber": "^7.0.0", "@serenity-js/core": "^2.25.7", "@s ...

Creating nested routes with parameters in NestJS is a powerful feature that allows for dynamic routing

I have a requirement to create an API with routes that share a common URL part along with a parameter. For my particular case, the routes should follow this structure: /accounts/:account/resource1/:someParam /accounts/:account/resource2/:someParam/whate ...

How can I determine the data type of an Array element contained within an Interface member?

Is there a way to extract the type of key3 in MyInterface2 and use it in key3Value, similar to key2Value? interface MyInterface { key1: { key2: string } } const key2Value: MyInterface['key1']['key2'] = 'Hi' / ...

The absence of definition for onSubmit is causing an issue in Angular 6

I am encountering an issue with validating the sign-in form as it is showing an error stating onSubmit is not defined. Below is the code snippet: import { Component, OnInit } from '@angular/core'; import { FormArray, FormControl, FormGroup, Vali ...

"HTML glitches in Onsen 2: A Dynamic Dilemma

During runtime, my app context is dynamically generated. In Onsen 1.3, I utilized the following function to create and compile the HTML: $scope.generateFrom = function (div) { var el = div; var html = HTMLGenerator.getHTML(); el.in ...

Crafting a nested path type in Typescript

Currently, I am working on developing a recursive type in TypeScript to iterate through every potential route path, even nested paths, from a provided route configuration. However, I have hit a roadblock with type constraints and inference. The routes are ...

Best practice for integrating Typescript into an established ASP.NET 4 Webforms project

Currently, I am working on an older asp.net 4.0 Webforms project using Visual Studio 2015. My goal is to transition from using Javascript to TypeScript for certain client side code tasks. While I have experience using TypeScript in projects outside of Vis ...