What are the steps to implementing dependency injections in Angular 2?

I have created an AuthService and I am looking to utilize it across all my components. My goal is to maintain a global userLoggedIn value for all components. However, I encountered the following error when running the script - Property 'userLoggedIn' does not exist on type 'AuthService'.

import { Component, Input, Inject, ReflectiveInjector, Injectable} from '@angular/core';
@Injectable()
export class AuthService {
    static userLoggedIn : boolean = false;
    
    static changeLoginStatus(status: boolean){
        this.userLoggedIn = status;
    }
}

Component file -

import { Component, OnInit, Inject, ReflectiveInjector } from '@angular/core';
import { FormGroup, FormBuilder, Validators, AbstractControl, FormControl } from '@angular/forms';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';

import { CustomValidators } from '../common/validations.ts';
import { AuthService } from '../injectables/authservice.ts';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
    loginForm : FormGroup;
    data : any;

    constructor(private http: Http, fb: FormBuilder) {
    this.loginForm = fb.group({
      'email':[null, Validators.compose([Validators.required,CustomValidators.emailFormat])],
      'password':[null, Validators.compose([Validators.required])],
    });
    }

    ngOnInit() {

    }

    submitLoginForm(value: any){
        console.log(value);
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        let body = JSON.stringify(value);

       this.http.post(
        'http://192.168.1.90/articles/data/post/',
        body)
      .subscribe((res: Response) => {
        this.data = JSON.stringify(res);
        console.log('---->'+res.json().data.email);
        localStorage.setItem('email', res.json().data.email);
        localStorage.setItem('userID', res.json().data.id);
        localStorage.setItem('name', res.json().data.name);
        localStorage.setItem('loginStatus', 'true');
        
        AuthService.changeLoginStatus(true);
        console.log('localstorege item ---->'+localStorage.getItem('email'));
      });
      return false;
    }

}

Answer №1

Adjust the AuthService to the following:

export class AuthService {
    isLoggedIn: boolean = false;
    updateLoginStatus(status: boolean){
        this.isLoggedIn = status;
    }
}

In order for dependency injection to function properly, you need to include AuthService as a parameter in the constructor of any component that uses it, like so:

constructor(
   private auth: AuthService, // <-- here
   private http: Http, 
   fb: FormBuilder
) {
   // ...
}

submitLoginForm(value: any) {
   // ...
   this.auth.updateLoginStatus(true); // <-- here
}

Additionally, ensure that you add AuthService to the providers array in your NgModule, for example:

@NgModule({
   // .....
   providers: [ AuthService ]   // <-- here
   // .....
})

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

Discover the secrets to dynamically swapping out all columns in a Data Table with Angular2+

Whenever changes or events occur outside of the Data Table, my requirement is to replace all the columns. When the data table is displayed for the first time, it shows selected columns based on an event. However, if I select another option, the new column ...

What is the method for creating pipes that filter multiple columns?

My pipe is designed to work exclusively for the "name" column and not for the author anymore. transform(items: Book[], filter: Book): any { if (!items || !filter) { return items; } // Filter items array; keep items that match and retu ...

The element's 'nativeElement' property cannot be accessed because it is undefined

I have a scenario where I have a parent component and a child component. I am trying to access the DOM element of the Child component from the Parent component, but I keep encountering an issue with the native element being undefined. export class ChildCom ...

Navigating back to the starting point

I'm experiencing an issue while trying to navigate using the Router.navigate method. Despite following all instructions meticulously, whenever I attempt to route via API, it reloads the root page. Within my RootComponent implementation, I am utilizin ...

"Connecting multiple URLs to the same router link: A step-by-step guide

I am currently working on a small test project in Angular and I aim to incorporate a side navigation using Angular router outlet. My goal is to have two links: <a class="nav-link text-white" [routerLink]='["/link/to/one"]' routerLinkActive="a ...

Is it possible to execute "green arrow" unit tests directly with Mocha in IntelliJ IDEA, even when Karma and Mocha are both installed?

My unit tests are set up using Karma and Mocha. The reason I use Karma is because some of the functionality being tested requires a web browser, even if it's just a fake headless one. However, most of my code can be run in either a browser or Node.js. ...

What are the steps to resolve the MSB4132 error in MSBUILD on a Windows 10 system?

Currently working on an Angular 2 project while using Windows 10. When I ran npm install, I encountered this error message: MSBUILD : error MSB4132 MSBUILD : error MSB4132: The tools version "2.0" is unrecognized. The available tools versions are "12. ...

Issues with code functionality following subscription via a POST request

I'm currently facing an issue with a service that utilizes an HTTP post request to communicate with the database. Unfortunately, when I try to implement this in my .ts file, nothing seems to happen after subscribing to the post. The post itself works ...

Preventing JavaScript Compilation for a Specific Folder using tsconfig: A Step-by-Step Guide

To create my own npx package, I'm currently working on converting my .ts files into .js. The purpose of the application is to generate TypeScript templates for users based on their selected options. In this app, there's a CLI called 'index.t ...

The process of extracting a value from an array of objects encountered an error due to the undefined object

I am looking to extract the value from an array within an object while also implementing error checking. The code I currently have checks if a specific key exists in the object and if the value associated with that key is of type array. If both condition ...

Encountering a compilation error while compiling using Angular Ivy

Encountering a compile time error in my Angular 8 project when enabling angular Ivy. Upgrading to version 8.1.0 did not solve the issue, and I continue to receive the following error: D:\Users\Backup>ng build shared Building Angular Package B ...

Leveraging React's state to enable temporary invalid numeric input handling

My current approach may be flawed, but I aim to have a parent component and a child component, where the child contains an input field for users to enter numbers. The callback function of the parent component will only be triggered for valid numbers, as ve ...

Tips for defining the anticipated server response solely based on status and cookie

I am using Redux Toolkit Query to occasionally refresh the jwt token: import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react"; export const refreshApi = createApi({ reducerPath: "apiSlice", baseQuery: fetchBaseQuer ...

How can I show the localStorage value in an HTML5 template using Angular2?

I have two keys stored in localStorage and I want to display one of them on my template. I'm having trouble accessing these values. I even created an interface specifically for storing the value of the currentUser key from localStorage. How should I g ...

Using Angular 5 with Typescript to generate and return an array of freshly instantiated typed objects

My backend service provides me with "moments," and I have two functions to handle this data. One is a get() method that returns a single object, and the other is a search() method that returns an array of objects. moment.service.ts The get method success ...

What is the best way to retrieve class members using component properties?

I am looking to implement a mixin for setting the header and meta data in my project. I recently discovered vue-meta, which seems to work really well for this purpose. However, I am still getting acquainted with TypeScript and class-based components. How ...

The variance in module types within the tsconfig.json file

When configuring your project in tsconfig.json, you may come across the following options: { "compilerOptions": { "target": "es5", "module": "commonjs", "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": t ...

Improving the method of retrieving RTK result within getServerSideProps

Currently, I am utilizing RTK Query to make an API call within my getServerSideProps function. While I can successfully retrieve the result using the code snippet provided below, I find the process somewhat awkward. Additionally, the result lacks proper ty ...

Outdated compiler module in the latest version of Angular (v13)

After upgrading to Angular 13, I'm starting to notice deprecations in the usual compiler tools used for instantiating an NgModule. Below is my go-to code snippet for loading a module: container: ViewContainerRef const mod = this.compiler.compi ...

Using Lodash to eliminate objects from a list

I have a specific model for my list, it looks like this: Animal Model id name age gender city Within the animals[] = []; array that I am working with, I need to remove the fields name, age, and gender while keeping id and city. How c ...