vasanth kumar vasanth kumar - 16 days ago 5
TypeScript Question

How can I use dependency injections in angular2

This is my AuthService.How can I use this auth service in all my components. I want to maintain userLoggedIn value global for all my components.I am getting the below error, when I run this 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;
//call this function when login status changes
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 './rxjs-operators';

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;
//http : Http;

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');
//this.loginStatus = true;
//aService: AuthService;
AuthService.changeLoginStatus(true);
console.log('localstorege item ---->'+localStorage.getItem('email'));
});
return false;
}

}

Answer

Change your AuthService to

export class AuthService {
    userLoggedIn : boolean = false;
    changeLoginStatus(status: boolean){
        this.userLoggedIn = status;
    }
}

Dependency injection works through your constructor parameter. Any component which use AuthService should have it in its constructor parameter, for example

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

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

Also, make sure you use AuthService in your NgModule providers, for example :

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