角度7:未定义注入的服务

时间:2019-03-18 21:25:25

标签: angular typescript ecmascript-6 dependency-injection jhipster

我尝试在LoginService中注入AccountService,但不会这样做,accountService未定义,但另一方面authServiceProvider已定义。

相反,它完美地注入了footerComponent。

那么为什么将AccountService完美地注入FooterComponent并导致LoginService出现错误。

我不知道问题来自何处。

import { Injectable } from '@angular/core';
import { AccountService } from 'app/core/auth/account.service';
import { AuthServerProvider } from 'app/core/auth/auth-jwt.service';
@Injectable({ providedIn: 'root' })
export class LoginService {
    constructor(public accountService: AccountService, private authServerProvider: AuthServerProvider) {
        console.log(this.accountService); //  is undefined 
        console.log(this.authServerProvider); // is defined
}

这是AuthentificationService

@Injectable({ providedIn: 'root' })
export class AuthServerProvider {
    constructor(private http: HttpClient, private $localStorage: LocalStorageService, private $sessionStorage: SessionStorageService) {}

这是AccountService

@Injectable({ providedIn: 'root' })
export class AccountService {
    private userIdentity: any;
    private authenticated = false;
    private authenticationState = new Subject<any>();
    constructor(private languageService: JhiLanguageService, private sessionStorage: SessionStorageService, private http: HttpClient) {}

我尝试在其他组件中使用AccountService,并且注入完美

import { Component } from '@angular/core';
import { AccountService } from 'app/core';
@Component({
    selector: 'jhi-footer',
    templateUrl: './footer.component.html',
    styleUrls: ['./footer.component.scss']
})
export class FooterComponent {

    constructor( private accountService: AccountService) {
        console.log(this.accountService); // It is defined

    }
}

这是app.module.ts

import './vendor.ts';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { NgbDatepickerConfig } from '@ng-bootstrap/ng-bootstrap';
import { Ng2Webstorage } from 'ngx-webstorage';
import { NgJhipsterModule } from 'ng-jhipster';
import { AuthInterceptor } from './blocks/interceptor/auth.interceptor';
import { AuthExpiredInterceptor } from './blocks/interceptor/auth-expired.interceptor';
import { ErrorHandlerInterceptor } from './blocks/interceptor/errorhandler.interceptor';
import { NotificationInterceptor } from './blocks/interceptor/notification.interceptor';
import { SharedModule } from 'app/shared';
import { CoreModule } from 'app/core';
import { AppRoutingModule } from './app-routing.module';
import { HomeModule } from './home/home.module';
import { AccountModule } from './account/account.module';
import { EntityModule } from './entities/entity.module';
import * as moment from 'moment';
// jhipster-needle-angular-add-module-import JHipster will add new module here
import { JhiMainComponent, NavbarComponent, FooterComponent, PageRibbonComponent, ActiveMenuDirective, ErrorComponent } from './layouts';
@NgModule({
    imports: [
        BrowserModule,
        Ng2Webstorage.forRoot({ prefix: 'jhi', separator: '-' }),
        NgJhipsterModule.forRoot({
            // set below to true to make alerts look like toast
            alertAsToast: false,
            alertTimeout: 5000,
            i18nEnabled: true,
            defaultI18nLang: 'en'
        }),
        SharedModule.forRoot(),
        CoreModule,
        HomeModule,
        AccountModule,
        // jhipster-needle-angular-add-module JHipster will add new module here
        EntityModule,
        AppRoutingModule
    ],
    declarations: [JhiMainComponent, NavbarComponent, ErrorComponent, PageRibbonComponent, ActiveMenuDirective, FooterComponent],
    providers: [
        {
            provide: HTTP_INTERCEPTORS,
            useClass: AuthInterceptor,
            multi: true
        },
        {
            provide: HTTP_INTERCEPTORS,
            useClass: AuthExpiredInterceptor,
            multi: true
        },
        {
            provide: HTTP_INTERCEPTORS,
            useClass: ErrorHandlerInterceptor,
            multi: true
        },
        {
            provide: HTTP_INTERCEPTORS,
            useClass: NotificationInterceptor,
            multi: true
        }
    ],
    bootstrap: [JhiMainComponent]
})
export class AppModule {
    constructor(private dpConfig: NgbDatepickerConfig) {
        this.dpConfig.minDate = { year: moment().year() - 100, month: 1, day: 1 };
    }
}

这是core.module。

import { NgModule, LOCALE_ID } from '@angular/core';
import { DatePipe, registerLocaleData } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { Title } from '@angular/platform-browser';
import locale from '@angular/common/locales/en';
@NgModule({
    imports: [HttpClientModule],
    exports: [],
    declarations: [],
    providers: [
        Title,
        {
            provide: LOCALE_ID,
            useValue: 'en'
        },
        DatePipe
    ]
})
export class CoreModule {
    constructor() {
        registerLocaleData(locale);
    }
}

预先感谢您的帮助。

3 个答案:

答案 0 :(得分:6)

我也遇到了同样的事情,解决方案是用户 span

->在回调中传递箭头函数而不是常规函数。箭头函数没有自己的 this

常规函数和箭头函数here

之间的区别

答案 1 :(得分:3)

  

除非您一直在根注入器中提供服务,否则   在某些情况下,您希望仅在以下情况下才可以使用该服务:   消费者导入特定的@NgModule。

尝试在providers : [ ]的{​​{1}}中添加要注入的服务

core.module

,然后在您的AccountService中,将import { NgModule, LOCALE_ID } from '@angular/core'; import { DatePipe, registerLocaleData } from '@angular/common'; import { HttpClientModule } from '@angular/common/http'; import { Title } from '@angular/platform-browser'; import locale from '@angular/common/locales/en'; @NgModule({ imports: [HttpClientModule], exports: [], declarations: [], providers: [ AccountService, Title, { provide: LOCALE_ID, useValue: 'en' }, DatePipe ] }) export class CoreModule { constructor() { registerLocaleData(locale); } } 替换为@Injectable({ providedIn: 'root' })

@Injectable()

答案 2 :(得分:0)

HttpClientModule是HttpClient所必需的。只需导入AppModule。

response