为什么共享模块中的指令未定义?

时间:2019-02-21 10:51:40

标签: angular angular-directive angular-module

我正在使用angular 7应用程序中的共享模块,以便在其他模块中使用指令

import { Directive, OnInit, HostBinding, Input } from '@angular/core';

@Directive({
    selector: '[appServerSuccess]'
})

export class ServerSuccessDirective implements OnInit {
    @Input() appServerSuccess: string;
    @HostBinding()
    get innerText() {
       return this.appServerSuccess;
    }
    @HostBinding('class.success')
    get success () {
       return this.appServerSuccess.toLocaleLowerCase().includes('success');
    }

    constructor() {}
    ngOnInit() {}
}

shared.module.ts 中,我确实有指令的声明 export

import { NgModule } from "@angular/core";
import { ServerSuccessDirective } from './directives/server-success.directive';


@NgModule({
    imports: [ ],
    declarations: [ ServerSuccessDirective ],
    exports: [ ServerSuccessDirective ]
})

export class SharedModule {}

在每个 app.module.ts user.module.ts 中,我确实导入了 SharedModule

指令在应用程序的不同组件中使用。

<div [appServerSuccess]="msg"></div>

消息通过服务通过以下方式传递:

private messageSource = new BehaviorSubject('');
currentMessage = this.messageSource.asObservable();

constructor() {
    changeMessage(msg: string) {
        this.messageSource.next( msg );
    }
}

app.module 中的组件中,它可以正常工作,但是在 user.module 中的其他组件中,它引发以下错误:

  

无法读取未定义的属性'toLocaleLowerCase'

这意味着在 user.module 中无法识别指令。

模块中的导入,SharedModule中的声明导出是正确的。我要去哪里错了?

我一直在搜索,发现了这个question,看起来很相似,但是并不能解决我的问题。

2 个答案:

答案 0 :(得分:3)

默认的appServerSuccess未定义,因此更改

  

此行

 @Input() appServerSuccess: string;
  

此行

   @Input() appServerSuccess: string = '';

或其他任何默认的味精文本,请在此处查看有关typescript variables declarations

的更多信息

答案 1 :(得分:0)

问题已解决。它位于属于user.module的组件中,并使用/传递指令的 msg 属性值。

例如在组件 user-update.component.ts 中,我具有 msg 属性,该属性未初始化为msg: string。我将其更改为:msg = '';