typescript Angular 7:注入的服务未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/55230263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:48:59  来源:igfitidea点击:

Angular 7 : Injected service is undefined

angulartypescriptecmascript-6dependency-injectionjhipster

提问by Ridae HAMDANI

I tried to inject AccountService in the LoginService but it won't ,the accountService is undefined but in the other hand the authServiceProvider is defined .

我试图在 LoginService 中注入 AccountService 但它不会, accountService 未定义但另一方面 authServiceProvider 已定义。

Contrarily it injected perfectly in footerComponent.

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

So why the AccountService is injected perfectly in FooterComponent and it bugs in the LoginService.

那么为什么在 FooterComponent 中完美地注入了 AccountService 并且在 LoginService 中出现了错误。

I do not know where the problem came from .

我不知道问题出在哪里。

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
}

This is the AuthentificationService

这是身份验证服务

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

This is the AccountService

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

I tried to use AccountService in other component and it injected perfectly

我尝试在其他组件中使用 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

    }
}

this is the app.module.ts

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

and this is the core.module .

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

Thanks in advance for your help.

在此先感谢您的帮助。

采纳答案by ZINE Mahmoud

You should always provide your service in the root injector unless there is a case where you want the service to be available only if the consumer imports a particular @NgModule.

您应该始终在根注入器中提供您的服务,除非您希望服务仅在消费者导入特定 @NgModule 时可用。

try to add your service you want to inject in providers : [ ]in your core.module

尝试添加你的服务要注入的providers : [ ]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: [
        AccountService,
        Title,
        {
            provide: LOCALE_ID,
            useValue: 'en'
        },
        DatePipe
    ]
})
export class CoreModule {
    constructor() {
        registerLocaleData(locale);
    }
}

and in your AccountService replace @Injectable({ providedIn: 'root' })with @Injectable()

并在您的 AccountService 中替换 @Injectable({ providedIn: 'root' })@Injectable()

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

回答by Carherpi

The same thing happened to me, the solution was the one mentioned by the user span

同样的事情发生在我身上,解决方案是用户跨度提到的

-> Passing arrow function instead of regular function in the callback. Arrow functions don't have its own this.

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

Difference between regular functions and arrow functions here

常规函数和箭头函数的区别在这里