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

问题描述 投票:0回答:2

我在角度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中,我确实有一个声明和导出的指令:

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>

msg通过服务传递:

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,看起来有点类似,但它没有解决我的问题。

angular angular-directive angular-module
2个回答
3
投票

初始化的appServerSuccess的默认值是undefined,因此在从父组件传递值之前为其指定一个值。

改变这一行

 @Input() appServerSuccess: string;

到这条线

 @Input() appServerSuccess: string = '';

或任何其他string作为默认值。

看看有关typescript variables declarations的更多信息


0
投票

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

所以例如在一个组件user-update.component.ts我有msg属性,没有初始化像:msg: string。我改为:msg = '';

© www.soinside.com 2019 - 2024. All rights reserved.