Access to the 'currentUrlTree' property is restricted to the 'Router' class as it is marked as private and cannot be accessed externally

Currently, I am in the process of developing a login feature using jwt. However, I am encountering an error when attempting to retrieve the current URL of the active route as shown below.

Error Message: [default] /Users/~/src/app/app.component.ts:51:75 Property 'currentUrlTree' is private and can only be accessed within the 'Router' class.

Source Code: app.component.ts

import {Component, NgZone, OnInit} from '@angular/core';
import {Router} from "@angular/router";
import {AuthService} from "./auth.service";
import {tokenNotExpired} from "angular2-jwt";

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})
export class AppComponent {
 constructor (
  private _router: Router,
  private _authService: AuthService,
  private _zone: NgZone
 ) {
}
ngOnInit():void {
 this._router.navigate(['signin']);
 this._authService.getLoggedInEvent().subscribe((val) => {

  if (val) {
    // User logged in
    this._zone.run(() => this._router.navigate(['stocklist']));
  } else {
    // User logged out
    this._zone.run(() => this._router.navigate(['signin']));
  }
 });
} 

routeIsActive(routePath: string) {
 let currentRoute = this._router.currentUrlTree.firstChild(this._router.currentUrlTree.root);

 let segment = currentRoute == null ? '/' : currentRoute.segment;
 return  segment == routePath;
}

logout() {
 this._authService.logout();
}

loggedIn() {
 return tokenNotExpired();
}
}

Answer №1

In the given passage, it is mentioned that 'currentUrlTree' is a private attribute. To retrieve the current URL, one can utilize another attribute such as Router.url.

For further insight on this topic, refer to the official documentation. The documentation highlights that 'currentUrlTree' is kept private and not accessible externally:

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

How can I subscribe to nested JSON objects in Angular?

I am seeking advice on working with a nested JSON object. Within our server, there is an object located at "/dev/api/sportstypes/2" structured like this; { "NBA": { "link": "https://www.nba.com/", "ticketPrice": 50 }, "UEFA": { ...

Declaring variables or fields with specific type restrictions

Imagine we have a generic interface: export interface IKeyValue<K, V> { key: K; value: V; } Now, our goal is to define a variable or field and restrict the types that can be used as K and V: public items: IKeyValue<K extends Type1, V ex ...

React JS displayed the string of /static/media/~ instead of rendering its markdown content

When I looked at the material UI blog template, I created my own blog app. I imported a markdown file using import post1 from './blog-posts/blog-post.1.md'; Next, I passed these properties to this component like so: <Markdown className=" ...

Leverage the event handler within a React Component when working with TSX tags

Is there a way to expose an event handler that is defined within a React Component in an HTML-like tag? For example: <MyComp param1="abc" param2="def" onDoSomething={this.someMethod} /> I am trying to define the onDoSomething event, but currently I ...

Differences between Integrated and Isolated Testing in Angular 2

Can you explain the key distinctions between Integrated testing and Isolated testing? In what scenarios would these testing methods be recommended for use? ...

Are you a skilled UI Designer looking to work with JHipster?

Just starting out with JHipster and I've generated my first Angular 2 project using JHipster 4.5.1. It's been an amazing journey so far! Now, I'm looking to customize the default JHipster generated Angular 2 pages and create my own custom p ...

Properties are determined by both the type and sub-type

A challenging TypeScript challenge. Exploring Multiple Discriminated Union Types This task involves intersecting multiple discriminated union types together, where there exists a relationship between "types" and their corresponding "sub-types." The Main Q ...

Utilizing Typescript and RequireJS for Incorporating jqueryui

Recently, I've been encountering issues with getting jQueryUI to function properly. Strangely enough, prior to attempting to integrate jQueryUI, using jQuery alone worked perfectly fine. The current problem I'm facing is receiving a "TypeError: ...

Getting the Full Error Message in Axios with React Native Expo

I'm encountering a network error while using Axios with React Native. Previously, when working with React JS on the web, I could console log the error or response and see all the details. However, in Expo, all I get is "Axios error: Network error" wh ...

What is the best way to explain a function that alters an object directly through reference?

I have a function that changes an object's properties directly: function addProperty(object, newValue) { object.bar = newValue; } Is there a way in TypeScript to indicate that the type of object is modified after calling the addProperty function? ...

What is the proper way to implement jest.mock in a describe or it block?

Using typescript and jest, I am faced with a scenario involving two files: users.service.ts, which imports producer.ts. In an attempt to mock a function in producer.ts, I successfully implement it. import { sendUserData } from "./users.service"; const pro ...

Testing Angular applications using Karma

After utilizing the yo angular 1 generator, it generated a landing page and some tests. However, I am facing an issue when trying to compile the code in VS as I receive an error stating that "module('fountainFooter');" is undefined. /// <refe ...

Utilizing custom hooks for passing props in React Typescript

I have created a unique useToggler custom hook, and I am attempting to pass toggle props from it to the button child in the Header component. However, when I try using toggle={toggle}, I encounter this error: Type '{toggle: () => void;}' is ...

Issue with Angular 6: Unable to locate identifier 'require' while trying to request xml2json node

Recently delving into Angular, I've been exploring the installed node modules and how to use them in a data.service.ts file. Everything below executes flawlessly! var isWindows = require('is-windows'); console.log("Is this windows? " + isWi ...

Cross-Origin Resource Sharing problem with identical URL

I encountered a CORS issue with my Angular 6 application running on port 4200 and using an API on port 3000. To address this, I implemented the following code snippet on the server side: app.use(function(req, res, next) { res.header("Access-Control-Allo ...

Tips for using a loop variable as an argument in a method call for an attribute reference

Within the html code of my component, I have the following: <div *ngFor="let image of images; let i=index;" class="m-image-wrapper"> <i class="fa fa-times m-delete-img" (click)="removeImage(i, {{image.docname ...

Is it possible to customize the appearance of a toast notification using Toastr beyond the default settings? If so, what options are available for creating

Working with Angular 9 and ngx-toastr has presented me with an interesting challenge. I am tasked with creating custom toast styles that differ significantly from the default ones provided by toastr. Each toast in the set will have unique border colors, f ...

Issue encountered during ng2-redux installation

While attempting to use the https://www.npmjs.com/package/ng2-redux link, I encountered an issue when running npm install redux ng2-redux --save. Here is the stacktrace of the error: npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\\Program Files& ...

Tips for incorporating live stock price updates into an Ionic application

Using a 3rd party API, I have successfully displayed a list of stock prices on cards. However, I am struggling to update the real-time data on each card with each second changes. I have attempted various methods, but the entire API is being fetched inste ...

Steps for configuring a splash screen in Ionic 4

I am in the process of migrating source code from Ionic 3 to Ionic 4. After copying the Ionic 3 resources folder to the Ionic 4 project, I noticed that the Cordova symbol is now appearing on the splash screen. See image here for reference I am c ...