Having trouble resolving all parameters for AuthService in Angular

Launching my angular app has hit a roadblock with this perplexing error. Despite attempts to troubleshoot by removing the auth service provider and constructor reference from my component, the issue persists. As a novice in angular, I'm struggling to pinpoint the mistake.

Error Message:

Can't resolve all parameters for AuthService: (?, ?, [object Object]).

Code Snippet - Component:

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../../Services/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers: [AuthService]
})

export class LoginComponent {

  isUserLoggedIn: boolean;
  emailAddress: string;
  password: string;
  invalidLogin: boolean;
  invalidText: string;

  constructor(private authService: AuthService, private router: Router) {

    if (authService.getCurrentUser() != null) {
      router.navigate(['/home']);
    }
  
  }

  login() {
    
    if (!this.authService.login(this.emailAddress.toString(), this.password.toString())) {
      this.invalidLogin = true;
      this.invalidText = "Wrong Email Address or password";
    }
    
  }

}

Code Snippet - Service:

import { Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { UserModel } from "../Models/UserModel";

export class AuthService {

    constructor(private router: Router, private http: HttpClient, @Inject('BASE_URL') private baseUrl: string) {}

    login(email: string, password: string) {

        const headers = {'Content-Type': 'application/json', };
        const body = { emailAddress: email, password: password };
        let userLoggedIn: Boolean = false;

        this.http.post<any>(this.baseUrl + "Api/Login", body, { headers }).subscribe(response => {
            
            if (response.username != null) {
                let user: UserModel
                user = response;
                this.router.navigate(['/home']);
                this.saveUserToLocalStorage(user);
                userLoggedIn = true
            }

        }, error => console.error(error)); 
        return userLoggedIn;
    }

    saveUserToLocalStorage(loggedInUser: UserModel) {
        sessionStorage.setItem("loggedInUser", JSON.stringify(loggedInUser));
    }

    getCurrentUser() {
        return sessionStorage.getItem("loggedInUser")
    }

    logout() {
        sessionStorage.removeItem("loggedInUser")
        this.router.navigate([''])
    }

    createUser(userData: UserModel) {}

    sendResetPasswordEmail() {}

}

Answer №1

In my opinion, the reason for this issue is due to your usage of Router in the constructor. To resolve this, you can make the following adjustments:

constructor(private readonly injector: Injector,
           ...) {}

public get router(): Router {
   return this.injector.get(Router);
}

Answer №2

I finally identified the issue. I needed to label my service class as @Injectable()

Here's how:

@Injectable()
export class SchoolService {
  ...
}

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

JSON object fails to iterate with ng-repeat

It must be the scorching temperature... Having a json object that I'm eager to loop through using ng-repeat, it should be straightforward, but alas! it's just not cooperating. Here's the HTML snippet: <a data-ng-repeat="x in template.m ...

The handler provided to Boost::asio::async_read_until is never triggered

I am attempting to establish a connection between two computers on a local network. One is using a slightly modified version of the Boost Asio C++ TCP asynchronous server sample, while the other is running NodeJS. tcp_client.js : var net = require(' ...

Tips for utilizing the getServerSideProps function

I want to improve the SEO friendliness of my page by utilizing the getServerSideProps method. Despite searching online, I couldn't find a specific example that fits my situation. I am uncertain about how to proceed since I currently have a useEffect m ...

Struggling with rendering components in REACT?

I'm encountering an issue with rendering the Butcher Shop component. I can't seem to pinpoint what's causing it to be null or undefined. Can someone help me identify the mistake? Nothing is showing up on the DOM and I keep getting this error ...

Hide the 1, 2, 3 page buttons in Datatables pagination and instead display only the Next and Previous buttons for navigation

I recently implemented datadables.net pagination for my HTML table. I am looking to customize the pagination buttons by hiding or removing the 1, 2, 3 ... buttons and only display Next and Previous Buttons. Is there a way to achieve this by setting paging ...

AngularJS - the element of surprise in execution sequence

Encountering a puzzling issue that exclusively affects Internet Explorer (any version) and not Chrome. An "items" array is stored within the "doc" object. Users have the capability to edit items, which essentially deletes the item but retains its content ...

unable to successfully execute jQuery popup close functionality

I have a button on my mobile site that I want to function as follows: Upon clicking the button, a popup should appear with text and an OK button. When the OK button is clicked, the popup should disappear without affecting the page. My code for this functi ...

jQuery not being applied to dynamically added dropdown element

I am currently utilizing bootstrap and jquery within my react project. I have a button that, when clicked, should transform into a dropdown field. The dropdown functions properly when placed statically, but the functionality is lost once it is dynamically ...

Error in ag-Grid CSV export feature displaying incorrect file names

Currently, I am coding in Typescript using Angular 2 along with ag-Grid (non-enterprise variant). An issue has arisen with the export feature of ag-Grid and I was wondering if someone could offer some assistance. If there is only one Grid on the form, ex ...

Using a custom TemplateRef in NgxDatatable

In the project I am currently working on, the tables have a specific wrapper around them. To prevent repetition of code, I am seeking a method to create a template where each component passes an ng-template that will be rendered within the custom table tem ...

A guide on utilizing multer-sftp for downloading files

I've been working on this code, but after searching online I still haven't found a way to download a file from the remote server. I can successfully upload files to the server, but downloading them is posing a challenge. var storage = sftpStorag ...

Mapping choices array in ReactJS using the id as a key reference

Looking for assistance with JavaScript as I am relatively new to it. I have a page displaying scheduled exams, and clicking on "Learn more" opens a modal where you can edit exam details. Currently, the modal displays selected equipment and allows changing ...

The JQUERY Uncaught Error: Syntax error message popped up when trying to access an unrecognized expression on the javascript: void(0)

I've encountered an issue after upgrading to jQuery 3.4.1 while using bootstrap 3. The console keeps showing this error: Uncaught Error: Syntax error, unrecognized expression: # Here is the section of code causing the error: <div class="btn-grou ...

How can I decrypt a JWT token using Angular?

One of my current tasks involves decoding a jwt token that is provided by the API during the login process. Can anyone provide guidance on how to decode a jwt token in an Angular application? ...

I need help figuring out how to get a horizontal scrollbar positioned at the top of a div to function properly once the content has been loaded using ajax

HTML CODE <div id="scrollidout" style="overflow: auto; overflow-y: hidden; "> <div id="scrollidin" style="padding-top: 1px; height: 20px; width: 1000px">&nbsp;</div> </div> <div class="resultcontent" style="overflow ...

How can one create a hidden color box?

$.colorbox({ href:"/check.html", transition:"elastic", speed: 150, innerWidth:"910", iframe:true, fastIframe:false, fixedPosition:fixedPos, onComplete:function(){ var $ ...

XState: linking together multiple promises seamlessly without needing intermediate states

After reading the Invoking Multiple Services section, it seems that despite being able to invoke multiple promises, they appear to be triggered without waiting for the previous one to complete in my own tests. // ... invoke: [ { id: 'service1' ...

Encountering issues with loading series on Highchart in Angular 4 due to duplication restrictions

I recently integrated highchart into my Angular 4 application, but I encountered a problem where the same series is being loaded twice. The issue seems to be related to the addSeries method, which is triggered by the @Input() set stressTestResults declarat ...

Creating a hyperlink dynamically within an Angular TypeScript file can be easily achieved

I am looking to create a dynamic hyperlink within the component (in the .ts file) using a for loop inside a function. I understand that this can be achieved by utilizing *ngFor loop in the template. For instance - <div *ngFor="let rec of item.R ...

What is the procedure for selecting an element based on its child containing specifically filtered text?

Imagine a webpage with the following elements: <div data-search="type1"> any HTML <!-- .click is a child of any level --> <span class="click" data-source="page1.html">blue</span> <!-- let's call it "click1 ...