Encountering crashes while initializing the router in the constructor of a service in Angular 4.3

I've been scratching my head over this problem. It seems like I'm overlooking something simple.

Let me show you what's inside my home.component.ts file:


import { Component, OnInit } from '@angular/core';
import { AuthService } from './../../services/auth/auth.service'
import { TestAuthService } from './../../services/auth/testauth.service'

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  providers: [AuthService, TestAuthService]
})
export class HomeComponent implements OnInit {

  constructor(public authService: TestAuthService) 
  { 
    //  authService.login();
  }

  ngOnInit() {
  }

  loginClick() {
    this.authService.login();
  }

}

Things were working perfectly until I introduced TestAuthService to my component. Now, the main AuthService is no longer in use. Even removing or keeping the import doesn't change anything.

Next, let's take a look at testauth.service.ts:


import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import 'rxjs/add/operator/filter';
import * as auth0 from 'auth0-js';

@Injectable()
export class TestAuthService {
    auth0 = new auth0.WebAuth({
        clientID: 'clientIdKeyString',
        domain: 'legitemail.auth0.com',
        responseType: 'token id_token',
        audience: 'https://legitemail.auth0.com/userinfo',
        redirectUri: 'http://localhost:4200/callback',      
        scope: 'openid'
      });

      constructor(**private router: Router**) {}

      public login(): void {
        this.auth0.authorize();
      }

}

This uses auth0 which was installed via npm using:

npm install --save auth0-js

The reference is included in my .angular-cli.json file. When the constructor is left empty, everything works fine. But when I include the router in the constructor (the part I bolded), the entire screen crashes.

I can't figure out why adding the router to the constructor causes the page to fail loading completely. Simply removing the bolded "Router" parameter makes it work again.

The error message reads:

ng:///AppModule/AppComponent.ngfactory.js:7 ERROR Error: No provider for Router!

Answer №1

SOLUTION:

According to comments from JB Nizet, it is essential to include a RouterModule in the primary NgModule.

In the file app.module.ts

I made the following addition:

import { RouterModule } from '@angular/router';

After which, I included it in my list of imports:

imports: [
  BrowserModule,
  BrowserAnimationsModule,
  AppMaterialModule,
  RouterModule.forRoot([])
],

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

Trouble arises in AWS Code Pipeline as a roadblock is encountered with the Module

After many successful builds of my Angular project, it suddenly fails to build on AWS Code Build. I reverted back to a commit before any recent changes, but the error persists. When I run ng build --prod locally, it works fine. However, during the pipeline ...

Encountering an ExpressionChangedAfterItHasBeenCheckedError in Angular 6 when selecting an option from a dropdown menu

How can we fix the error mentioned below through code changes? Situation An input dropdown UI is safeguarded against unintentional value changes by a modal. However, triggering an event (such as click or focus) on the dropdown leads to the ExpressionChan ...

Using NextJS's API routes to implement Spotify's authorization flow results in a CORS error

I am currently in the process of setting up the login flow within NextJS by referring to the guidelines provided in the Spotify SDK API Tutorial. This involves utilizing NextJS's api routes. To handle this, I've created two handlers: api/login.t ...

Nested ControlGroup in Angular2's ControlArray

I've hit a roadblock trying to iterate through a ControlArray that has Controlgroups in a template. In TypeScript, I successfully created the ControlArray and added some ControlGroups by looping over data fetched from an API. The console displays the ...

The "ngx-places" directive does not have an "exportAs" setting

I recently added the ngx-google-places-autocomplete module to my project. However, upon configuring it, I encountered the following error: core.js:14597 ERROR Error: Uncaught (in promise): Error: Template parse errors: There is no directive with "expo ...

NextImage's ImageProps is overriding src and alt properties

I've created a wrapper called IllustrationWrapper that I'm utilizing in different components. import Image, { ImageProps } from 'next/image'; const getImageUrl = (illustrationName: string) => { return `https://my-link.com/illustra ...

Retrieve user roles from OpenID Connect client

Utilizing oidc-client for authentication in my application with Angular and ASP.NET Core 3.1. Is there a way to retrieve the user roles from ASP.NET using oidc client? ...

When using Konva getContext('2d') to retrieve image data, the data returned may be incorrect when viewing the image at varying resolutions and levels of zoom

Recently, I began using Konva and everything was functioning properly. However, when I opened the same HTML page on a 1920x1080 monitor with 150% zoom, I noticed that the data points array was incorrect at this resolution. layer.getContext('2d') ...

I am experiencing difficulties with implementing Angular material components in my project

I recently encountered an issue while trying to integrate angular material into my project. Despite importing the MatFormFieldModule, I received the following error: ERROR in src/app/login/components/login/login.component.html:2:1 - error NG8001: &apo ...

Exploring ways to send data to WebView in Flutter

How can I pass the location obtained in my Flutter app to a WebView for further processing within the opened site? var userLocation = Provider.of<UserLocation>(context); Here is my WebView setup: WebView( initialUrl: widget.url, javasc ...

Tips for configuring Angular 2 to send all requests in the form of application/x-www-form-urlencoded

My experience with Angular 1 has helped me in understanding how to implement a similar solution, but I'm stuck on the final step. Just like before, the backend developer for our application is set up to accept requests with type application/x-www-for ...

Is there a way to execute a code snippet just once when focusing on a specific field?

<form id="myForm"> <label for="fname">First name:</label><br> <input type="text" id="fname" name="fname"><br> <label for="mname">Middle name:</label> ...

Link a YAML file with interfaces in JavaScript

I'm currently learning JavaScript and need to convert a YAML file to an Interface in JavaScript. Here is an example of the YAML file: - provider_name: SEA-AD consortiumn_name: SEA-AD defaults: thumbnail Donors: - id: "https://portal.brain ...

Is it possible to limit the items in a TypeScript array to only accept shared IDs with items in another array?

I'm creating an object called ColumnAndColumnSettings with an index signature. The goal is to limit the values of columnSettings so that they only allow objects with IDs that are found in columns. type Column = { colId: string, width?: number, s ...

Issue with Material UI v5: "spacing" property not found on custom theme object

My current setup involves using version 5 of material ui, where I have customized a theme and applied it to all my components. However, when trying to add padding to a paper element in one of my components based on the theme, I encountered the following e ...

"Ionic Calendar 2 - The ultimate tool for organizing your

I am using a calendar in my Ionic app that retrieves events from a database through an API. var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://portalemme2.com.br/SaoJoseAPI/agenda', true); this.http.get('http://portalemme2.c ...

Using Angular 4: Redirecting Menu to Component with Electron

I am currently working on my first project using Angular 4 and Electron to develop a desktop application. One of the challenges I'm facing is figuring out how to redirect to a specific component when a submenu item is clicked after overriding the ele ...

Is it possible to specify broad keys of a defined object in TypeScript using TypeScript's typing system?

const obj: {[key: string]: string} = {foo: 'x', bar: 'y'}; type ObjType = keyof typeof obj; Is there a way to restrict ObjType to only accept values "foo" or "bar" without changing the type of obj? ...

Guide to organizing the table according to the values (timestamps) in a specific column

In one of the tables I'm working with, there is a column called uploadedOn. You can see it in action here: https://stackblitz.com/edit/angular-ivy-tntvst?devToolsHeight=33&file=src/app/app.component.ts 1: https://i.stack.imgur.com/aQ6wh.png. My g ...

Discover the method for dynamically setting the rangeSelector's min and max values multiple times in Angular Highcharts

I'm looking to dynamically set the range of an angular highstock chart by interacting with another component such as a table or button. For example, attempting to use setExtremes for selecting range T1 or T2 does not seem to work properly in this cod ...