Angular 2 DI错误

标签 angular dependency-injection

不知何故,DI 无法为我实例化服务。 我收到错误 TS2339:属性“authenticationService”在类型“LoginComponent”上不存在

如何正确实例化 AuthenticationService?我认为在提供程序的 app.module.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;
    }

}

这是 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);
    }
}

应用程序模块.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 {
}

最佳答案

像这样更改构造函数:

constructor(private authenticationService: AuthenticationService){}

以便您可以使用 this

在构造函数外部访问 authenticationService

注意:您也可以使用 constructor(public authenticationService: AuthenticationService){} 注入(inject)只需要一个 public/private 标识符即可使用 this

访问

关于Angular 2 DI错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41247957/

相关文章:

javascript - AngularJS - 类型错误 : Cannot read property 'canonicalUrl' of undefined

Angular 2/4 - 从 DOM 中删除组件,但保留在内存中

angular - 类型 'HTMLElement' 的参数不可分配给类型 'CanvasImageSource' 的参数

c# - 为什么尝试在 Windsor .net core 中注册作用域组件时会发生 'Scope was not available' 错误?

c# - 使用 Autofac,如何在调用 RegisterControllers 后在单个 mvc Controller 上启用属性注入(inject)?

angular - Angular 2 View Child/Element Ref选择两次相同的元素

php - 如何连接 Angular 2 和 php 后端 (mysql)

c# - 如何在涉及异步调用的 ASP.NET Core 中初始化作用域注入(inject)类

php - Symfony2 - 在 services.xml 中导入 config.yml

java - Spring DI 同时有两个构造函数