Encountering the NullInjectorError when Angular 17 is unable to find a provider for the function(options)

I'm new to Angular (version 17) and encountered an error: ERROR Error [NullInjectorError]: R3InjectorError(Standalone[_LoginPageComponent])[function(options) { -> function(options) { -> function(options) { -> function(options) { -> function(options) {]: [1] NullInjectorError: No provider for function(options) {! The error occurs when trying to add private router: Router to the constructor() in login-page.component.ts.

login-page.component.ts

import { CommonModule} from '@angular/common';
import { Component, OnInit} from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { AuthService } from '../shared/layouts/services/auth.service';
import { Subscription } from 'rxjs';
import { Router } from 'express';

@Component({
  selector: 'app-login-page',
  standalone: true,
  imports: [ReactiveFormsModule, CommonModule],
  templateUrl: './login-page.component.html',
  styleUrl: './login-page.component.css'
})
export class LoginPageComponent implements OnInit{
  form : FormGroup
  aSub: Subscription
  constructor(private auth: AuthService, private router: Router) {
  }

  ngOnInit(): void {
    this.form = new FormGroup({
      email: new FormControl(null, [Validators.email, Validators.required]),
      password: new FormControl(null, [Validators.minLength(6), Validators.required])
    })
  }
  

  onSubmit() {
    this.form.disable()

    this.aSub = this.auth.login(this.form.value).subscribe({
      next: (result) => {
      },

      error: (error) => {
        console.log(error)
        this.form.enable()
      }
    })
  }
}

app.config.ts

import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';
import { provideClientHydration } from '@angular/platform-browser';
import { provideHttpClient, withFetch } from '@angular/common/http';

export const appConfig: ApplicationConfig = {
  providers: [provideRouter(routes), provideClientHydration(), provideHttpClient(withFetch())]
};

auth.service.ts

import { Injectable } from "@angular/core";
import { User } from "../interfaces";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
@Injectable({
    providedIn: 'root'
})
export class AuthService {

    constructor(private http: HttpClient) {    
    }

    register() {

    }

    login(user: User): Observable<{token: string}> {
        return this.http.post<{token: string}>('http://localhost:5000/api/auth/login', user)
    }
}

Please assist me in resolving the issue. Thank you!

Answer №1

It's crucial to import <code>@angular/router
when working with Router.

Update your code snippet:

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

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

Creating Typescript type definitions for any object properties

Struggling to find the correct TS syntax with Typescript 3.7.3. I have a random object, for example: var obj = { one: ..., two: ... three: ... }; I want to create a type that includes all keys from that object, like this: type ObjKeys = &ap ...

Function that recursively checks for the existence of an ID within a nested object structure

I need assistance in developing a function that can determine whether the link ID of an object or any of its children match a specific ID. For instance, if the link ID for Product paths is 51125095, the function should return true when this ID is passed in ...

What is the process for generating a subpage within the main page without the need to navigate away from the primary

On my main page, I have a login button. Instead of redirecting the user to a new page, I want it to simply display a login box. You can see an example of this on medium.com when you click on 'sign in'. Is it possible to achieve this with only HTM ...

Modifying deeply nested properties in Vue.js

Within my Vue.js application, I've created a method to update the src attribute of images whenever a file is chosen from a file input field. This method is triggered like so: <input type="file" accept=".jpg,.png" @change="updateSrc($event, 'p ...

Storing extensive JSON data with AJAX, jQuery, and Java

Currently, I am utilizing jQuery AJAX to call a server-side method and sending a JSON string to the controller. Everything works smoothly when the JSON size is small, but as soon as it exceeds 7kb, the server side rejects the JSON string. I suspect that t ...

Attempting to convert the code from react documentation into class components within a react-create-app, but encountering unexpected behavior

Hey there! I'm currently diving into the world of React and challenging myself by rewriting all the code samples from the documentation in a local react-create-app. However, I've hit a roadblock with this section on the Doc, you can find the code ...

Leveraging Facebook Pixel within a DNN-powered website

Is there a way to integrate the Facebook pixel into a website created using the DNN platform? ...

Setting a blank value or null equivalent to a field: Tips and tricks

Here is the component state that I am working with: interface Person { name: string; surname: string; } interface CompState{ //...fields ... person?: Person; } render() { if(this.state.person){ const comp = <div>{this. ...

A sophisticated approach to implementing a search functionality within a complex JSON structure containing nested arrays using JavaScript

Searching for data in JSON format: { "results": { "key1": [ { "step": "step1", "result": "pass" } , { "step": "step2", "result": "pending" } ...

Include the aria-labelledby attribute in the jQuery Datatable Pagination

Check out the HTML output created by the Jquery Datatable plug-in for pagination(https://datatables.net/plug-ins/pagination/full_numbers_no_ellipses): <div class="dataTables_paginate paging_full_numbers" id="my-table_paginate" aria-l ...

Managing extensive geographical information through HTTP

What is the most efficient way to transmit a substantial volume of map information via HTTP for rendering on the client side? There must be a more effective approach than simply transmitting a JSON file containing all map data. I am interested in how maj ...

Points in an array being interpolated

I am currently working with data points that define the boundaries of a constellation. let boundaries = [ { ra: 344.46530375, dec: 35.1682358 }, { ra: 344.34285125, dec: 53.1680298 }, { ra: 351.45289375, ...

Why don't inline style changes implemented by JavaScript function properly on mobile browsers like Chrome, Dolphin, and Android?

View the jsFiddle here Issue on PC/Windows browser: When performing action, h1 header "gif" disappears and video starts playing. Problem on mobile devices: The gif does not disappear as expected but the video still plays indicating that JavaScript is fun ...

What is the best way to create a layout with two images positioned in the center?

Is it possible to align the two pictures to the center of the page horizontally using only HTML and CSS? I've tried using this code but it doesn't seem to work: #product .container { display: flex; justify-content: space-between; flex-w ...

What is the best way to create a seamless Asynchronous loop?

Adhering to the traditional REST standards, I have divided my resources into separate endpoints and calls. The primary focus here revolves around two main objects: List and Item (with a list containing items as well as additional associated data). For ins ...

Component opens MatSnackBar in various styles

I've been seeking a method to achieve the following: incorporating a custom SnackBar for displaying notifications. After consulting the official documentation (here), I successfully created a basic Snackbar with customized settings. this.snackBar.ope ...

Error in Typescript syntax within a CommonJS/Node module: Unexpected colon token found in function parameter

After validating the file with TS, there are no more errors. However, during runtime, I encounter an "Unexpected token ':'" error on any of the specified TS, such as immediately erroring on function (err: string). The following are my build and ...

Chaining updateMany() calls in MongoDB while ensuring synchronous response handling

I have encountered an issue while attempting to send 3 separate updateMany requests within a get request, each using a different query. While the first two requests work perfectly, the third updateMany request only functions as expected after refreshing th ...

Ways to reduce the size of images within a bootstrap carousel

I'm currently working on creating a carousel that will serve as a background image cover for my website, similar to the revolutionary slider in WordPress but without using a plugin. I am developing it specifically for my static website. The challenge ...

Issue with Slick Grid not updating after Ajax request

I need to update the data on a slick grid when a checkbox is clicked, using an ajax call to retrieve new data. However, I am facing issues where the slick grid does not refresh and the checkbox loses its state upon page load. Jsp: <c:if test="${info ...