简体   繁体   English

角度 2 DI 错误

[英]Angular 2 DI error

Somehow DI is failing to instantiate a service for me.不知何故,DI 未能为我实例化服务。 I am getting error TS2339: Property 'authenticationService' does not exist on type 'LoginComponent' .我收到错误 TS2339:属性 'authenticationService' 在类型 'LoginComponent' 上不存在

How do I properly instantiate the AuthenticationService?如何正确实例化 AuthenticationService? I thought that mentioning it in app.module.ts in providers would take care of that.我认为在提供者的 app.module.ts 中提及它会解决这个问题。

Thanks in advance提前致谢

Here is the AuthenticationService.ts:这是 AuthenticationService.ts:

import { Injectable } from '@angular/core';
import { /*HTTP_PROVIDERS, */Http, Headers } from '@angular/http';
import { AuthHttp } from 'angular2-jwt';

@Injectable()
export class AuthenticationService {

    jwtToken: any;

    constructor(public authHttp: AuthHttp) { }

    jwtHeader = new Headers({
        "Content-Type": "application/json",
        "alg": "HS256",
        "typ": "JWT"
    });


    Login(username: string, password: string) {

        console.log("from authService: " + username);

        this.authHttp.post('/api/AuthResponse',
            JSON.stringify({
                "username:": username,
                "password:": password
            }),
            { headers: this.jwtHeader }
        ).subscribe(data => this.jwtToken = data,
            () => console.log(this.jwtToken));

        return this.jwtToken;
    }

}

Here is the LoginComponent.ts:这是 LoginComponent.ts:

import { Component, OnInit } from '@angular/core';
import { AuthenticationService } from './../../services/AuthenticationService';
import { AuthHttp, AuthConfig/*, AUTH_PROVIDERS, provideAuth*/ } from 'angular2-jwt';

@Component({
    selector: 'login',
    template: require('./login.component.html')
})
export class LoginComponent implements OnInit {
    username;
    password;

    constructor(authenticationService: AuthenticationService){}

    ngOnInit() {
        // reset login status
        //this.authenticationService.logout();

    }

    //private authService: AuthenticationService = new AuthenticationService(new AuthHttp(new AuthConfig(), new Http());

    login()
    {
        console.log(this.username);
        console.log(this.password);
        this.authenticationService.Login(this.username, this.password);
    }
}

app.module.ts app.module.ts

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { UniversalModule } from 'angular2-universal';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AuthHttp, AuthConfig, AUTH_PROVIDERS, provideAuth } from 'angular2-jwt';

import { AuthenticationService } from './services/AuthenticationService';

import { AppComponent } from './components/app/app.component'
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { CounterComponent } from './components/counter/counter.component';
import { LoginComponent } from './components/login/login.component';


@NgModule({

    declarations: [
        AppComponent,
        NavMenuComponent,
        CounterComponent,
        FetchDataComponent,
        HomeComponent,
        LoginComponent
    ],
    imports: [
        UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
        FormsModule,
        HttpModule,
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
            { path: 'counter', component: CounterComponent },
            { path: 'fetch-data', component: FetchDataComponent },
            { path: 'login', component: LoginComponent },
            { path: '**', redirectTo: 'home' }
        ])
    ],
    providers: [
        AuthHttp,
        provideAuth({
            headerName: 'Authorization',
            headerPrefix: 'bearer',
            tokenName: 'token',
            tokenGetter: (() => localStorage.getItem('id_token')),
            globalHeaders: [{ 'Content-Type': 'application/json' }],
            noJwtError: true
        }),
        AuthenticationService
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
}

Change the constructor like this:像这样更改构造函数:

constructor(private authenticationService: AuthenticationService){}

so that you can access the authenticationService outside of the constructor with this这样您就可以访问authenticationService与构造之外this

Note: You can also use constructor(public authenticationService: AuthenticationService){} the injections just need a public / private identifier to be accessed with this注意:您也可以使用constructor(public authenticationService: AuthenticationService){}注入只需要一个public / private标识符即可通过this访问

if you trying to one module provider in another one then you should mention in in your routing file如果您尝试在另一个模块中使用一个模块提供程序,那么您应该在路由文件中提及

like you are trying "ABC" in "XYZ" then in XYZ routing class就像您在“XYZ”中尝试“ABC”然后在 XYZ 路由类中

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
  providers: [ABC_provider]
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM