Deliver router services for central Angular 2 elements

I am working on an ng2 app where I have the app/app.module and core/core.module. In the core modules, there are some modules that are used at the app top level and only once as mentioned in the official documentation. However, one of these modules requires the Router module for functionality related to routing.

The issue arises because the router is provided in App.module along with all the App routing configurations. The error message I encountered was "No provider for ActivatedRouteSnapshot from core/header/header.component."

How can I resolve this issue? Should I move the header from the core folder to the app folder or should I provide the router for core modules separately? Any guidance would be appreciated. Thank you.

P.S. After updating with the Router Module, I still encounter an error - No provider for RouterStateSnapshot!

Interestingly, the standard router and activatedRoute functionalities are working fine. When I remove RouterStateSnapshot from the constructor (and remove relevant console.log statements), everything works properly. It seems like the RouterModule is available, which is quite perplexing.

import { NgModule, Component, OnInit} from '@angular/core';
import { CommonModule } from '@angular/common';
//import { ROUTER_DIRECTIVES, Router } from '@angular/router-deprecated';
import { Router, ActivatedRoute, Params, RouterStateSnapshot } from '@angular/router';
/* ------- !Angular2 core  ---------*/

import {HTTPPatientsListService} from '%cgm_sharedServices%/http_patients_list.service';
/* ------- !Services  ---------*/

import { Config } from 'appConfig';
/* ------- !Config  ---------*/


@Component({
  selector: 't_breadcrumbs',
  template: `

      <h1>Bread</h1>

        <!--<div class="row wrapper border-bottom white-bg page-heading">-->
        <!--<div class="col-lg-10">-->
            <!--<h2>{{staticData.title}}</h2>-->
            <!--<ol class="breadcrumb">-->
              <!--<li>-->
                 <!--<a [routerLink]="['Dashboard']" tabindex="-1">{{staticData.homeName}}</a>-->
              <!--</li>-->
              <!--<li *ngFor="let crumbData of crumbsCollection; let last = last" [ngClass]="{'active': last}">-->
                  <!--<a *ngIf="!last" (click)="navigateTo(crumbData.urlPath)" tabindex="-1">{{crumbData.displayName}}</a>-->
                  <!--<span *ngIf="last"><b>{{crumbData.displayName}}</b></span>-->
              <!--</li>-->
            <!--</ol>-->
          <!--</div>-->
          <!--<div class="col-lg-2">-->
        <!---->
            <!--</div>-->
        <!--</div>-->
  
`,
  styles: [`
    .breadcrumb {
      background-color: #ffffff;
      padding: 0;
      margin-bottom: 0;
    }

    .breadcrumb > li a {
      color: inherit;
    }

    .breadcrumb > .active {
      color: inherit;
    }
  `]
})

export class BreadcrumbsComponent implements OnInit {




  // contains home static name and dynamic current component name
  private staticData = {
    'title': '',
    'homeName': 'Home'
  };

  private tempTitle: string;
  private crumbsCollection = [];

  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private routerStateSnap: RouterStateSnapshot,

    private config: Config,
    private httpPat: HTTPPatientsListService) { }


  ngOnInit() {
    console.log(this.activatedRoute);
    console.log(this.routerStateSnap);
  }


}


import { RouterModule } from '@angular/router';
@NgModule({
  imports: [ CommonModule, RouterModule ],
  declarations: [ BreadcrumbsComponent ],
  exports: [ BreadcrumbsComponent ]
})

export class BreadcrumbsModule {}

Answer №1

The recommended way to utilize the RouterStateSnapshot interface is as follows:

  constructor(router: Router) {
    const snapshot: RouterStateSnapshot = router.routerState.snapshot;
    //...
  }

It serves as an interface rather than a provider. It may be used in guards, but only because it is provided as a parameter in guard methods, not as something that can be injected (refer to CanActivate for instance).

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

Making a quick stop in Istanbul and NYC to collect a few important files

Setting up Istanbul/Nyc/Mocha for test coverage in my project has been a bit of a challenge. While I was successful in running Nyc, I noticed that not all the .ts files in my project were being picked up for test coverage. When I execute npm run coverag ...

Guide on connecting ngrx/store to an angular router guard

As someone who is new to ngrx/store, I am embarking on my initial project utilizing this tool. After successfully setting up my angular project with ngrx/store, I discovered how to dispatch a load action following the initialization of my main component: ...

Customizing the Style of Mat-Form-Field

I have designed a search bar using mat-form-field and attempted to personalize the appearance. Currently, there is a gray border-like region surrounding the input field and icons. Moreover, clicking on the input field results in a visible border: <form ...

In Bootstrap 3, rows are aligned on the same line

My issue is that two rows are coming on the same line in Bootstrap 3. Here is the code for a chat screen with two people: Code [<div class="row single-row mt-10" style="float: left !important;> <div class="col-2" styl ...

Show pictures stored in S3

I currently have an Amazon AWS S3 Bucket where I store images. Each object in the bucket has its own link, but when I try to open it in a browser, the image downloads instead of displaying directly on the site. This makes it challenging to view the images ...

Typeahead functionality in Angular UI Bootstrap that uses object properties to search and display

I have a similar item (recreation of Map): $scope.vehicles = { 1:{id:1, model:'Coupe'}, 2:{id:2, model:'Truck'}, 3:{id:3, model:'Hatchback'} } I want to utilize the property values in typeahead of ui bootstrap (whil ...

Concerning the utilization of the <mat-toolbar> element within Angular

Is the mat-toolbar in Angular going to persist across all components and pages of the application? Will it be present in every component throughout the application? <mat-toolbar color="primary"> <mat-toolbar-row> <span>Welcome to C ...

Managing input and output using a collaborative service

I've been working on refactoring some code that contains a significant amount of duplicate methods between two components. Component A is a child of component B, and they can be separate instances as intended. The issue I'm facing revolves around ...

Preventing users from entering past dates in Angular 6 - A step-by-step guide

Here is my current code snippet: ngOnInit() { let now = new Date(); this.date = formatDate(now, "dd/mm/yyyy",'en-US'); console.log("dateFormat :",this.date); } This is the html part of my code: <input type="date" [min]={{da ...

Leveraging Angular to incorporate HTML templates from one component into another component

I am currently working with two components. The first one is a table component, identified by the selector 'table-component', which has standard filtering capabilities. The second component is designed for displaying the table on a page. This me ...

The Elusive Glitch: IOS Encounter with Ionic 2

VIEW PROBLEM</p> I am currently developing an Ionic 2 application using Angular 2. Interestingly, I have encountered a peculiar issue that only occurs on one specific page of the app, but specifically on IOS devices. Strangely enough, only the visib ...

Dealing with routing problems within sub-routes using Angular 2 and Express, attempting to serve content from sub-folders

I am currently using Express to serve a local Angular2 application. To enable the Angular2 app to access various node_modules from Express, I have set up the following configuration: config.dependencies = [ { staticPath: './node_modules/@angular/&a ...

TypeScript compilation error caused by typing issues

My current setup includes typescript 1.7.5, typings 0.6.9, and angular 2.0.0-beta.0. Is there a way to resolve the typescript compile error messages related to the Duplicate identifier issue caused by typings definition files? The error message points ou ...

Retrieve fresh information every 30 seconds utilizing the useQuery hook in React

I am utilizing '@tanstack/react-query' to retrieve data in my React + Typescript application. Below is a snippet of my code, where I aim to fetch metric data every 30 seconds import { useQuery } from '@tanstack/react-query'; import ...

Getting the highest level object in a nested Angular component structure

Currently, I am in the process of developing a query builder using Angular that bears resemblance to the JQuery builder. However, I have encountered an issue related to emitting the data. Whenever I click on the addGroup or addRule buttons, a new group is ...

Obtain user information post-payment with Angular's latest Paypal Checkout 2.0 feature

My app is all set up to sell various items, with PayPal handling the payment process. In order to generate invoices, I need to access user details such as their name and address, which are stored by PayPal for each user. How can I retrieve this information ...

The result of comparing with `instanceof` in TypeScript

class Department { name: string; constructor(n: string) { this.name = n; } describe(this: Department){ console.log('department: ' +this.name); } } const frontend = new Department('frontend'); frontend.describe(); con ...

Angular 7 form does not automatically disable the button upon initialization

My current challenge involves disabling a button until a form is completely filled out. Surprisingly, everything works perfectly in Chrome and Firefox, but IE11 seems to be causing some issues. Below is the relevant code snippet: <div class="col-12"> ...

What is the process for setting up a subrouter using React Router v6?

This is the current React Router setup I am using: const router = createBrowserRouter([ { path: "/", element: ( <Page activeNav="home" > <Home /> </Page> ) }, { ...

What is the best approach for managing _app.js props when transitioning from a page router to an app router?

Recently, in the latest version of next.js 13.4, the app router has been upgraded to stable. This update prompted me to transition my existing page router to utilize the app router. In _app.jsx file, it is expected to receive Component and pageProps as pr ...