代码之家  ›  专栏  ›  技术社区  ›  k.vincent

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

  •  0
  • k.vincent  · 技术社区  · 7 年前

    我在Angular7应用程序中使用一个共享模块来使用 指令 在不同的其他模块中。

    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() {}
    }
    

    在 共享.module.ts ,我确实有一个 宣言 和 出口 指令:

    import { NgModule } from "@angular/core";
    import { ServerSuccessDirective } from './directives/server-success.directive';
    
    
    @NgModule({
        imports: [ ],
        declarations: [ ServerSuccessDirective ],
        exports: [ ServerSuccessDirective ]
    })
    
    export class SharedModule {}
    

    在每个 应用模块.ts 在 用户.module.ts ,我确实有 共享模块

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

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

    这个 味精 通过服务传递为:

    private messageSource = new BehaviorSubject('');
    currentMessage = this.messageSource.asObservable();
    
    constructor() {
        changeMessage(msg: string) {
            this.messageSource.next( msg );
        }
    }
    

    在组件中 应用程序模块 ,它工作正常,但在 用户模块 它引发以下错误:

    无法读取未定义的属性“toLocaleLowerCase”

    这意味着指令在 用户模块 .

    这个 进口 在模块中, 宣言 和 出口 in SharedModule是正确的。我哪里做错了?

    我一直在找,找到了这个 question ,看起来有点类似,但它没有解决我的问题。

    1 回复  |  直到 7 年前
        1
  •  3
  •   Ganesh    7 年前

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

    更改此行

     @Input() appServerSuccess: string;
    

    到这条线

     @Input() appServerSuccess: string = '';
    

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

    在这里查看有关 typescript variables declarations

        2
  •  0
  •   k.vincent    7 年前

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

    例如,在一个组件中 用户更新.component.ts 我有 味精 未初始化的属性,如: msg: string . 我把这个改成了: msg = '';

    推荐文章