如何在angular2中使用依赖注入

时间:2016-11-23 07:17:50

标签: angular typescript dependency-injection

这是我的AuthService.How如何在我的所有组件中使用此auth服务。我想为所有组件维护userLoggedIn值全局。当我运行此脚本时,我收到以下错误 - Property' userLoggedIn'类型' 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;
    }
}

组件文件 -

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;
    }

}

1 个答案:

答案 0 :(得分:0)

AuthService更改为

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

依赖注入通过constructor参数完成。使用AuthService的任何组件都应在其constructor参数中包含该组件,例如

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

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

此外,请确保在AuthService提供商中使用NgModule,例如:

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