【问题标题】:ngOnInit visibility of private memberngOnInit 私有成员的可见性
【发布时间】:2023-03-07 02:50:01
【问题描述】:

我有以下指令。

在 ngOnInit 中,this.word 和 this.components 都是“未定义的”。

谁能解释一下为什么?

import { Directive , Input, Output, ViewContainerRef, ComponentRef, DynamicComponentLoader, EventEmitter, OnInit, NgModule} from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { Widget } from '../widget.model';
import { CommentComponent } from './comment.component';


@Directive({selector: 'widget-factory'})
export class WidgetFactory {
  @Input() name: any;
  @Input() id: Number;

  @Output() loaded = new EventEmitter();

  private components: { 'Comment': CommentComponent };
  private word: "hello";

  constructor(
    private _dcl: DynamicComponentLoader,
    private _elementRef: ViewContainerRef
  ) {

  }

  ngOnInit() {
    // Get the current element 
    console.log(this.word);
    let component: any;
    //if(this[name] === 'Comment') {
      component = CommentComponent
    //}
    this._dcl.loadNextToLocation(CommentComponent, this._elementRef);
    console.log(this.name);

  }
}

深受启发:Outputting array of components in Angular 2

【问题讨论】:

  • 没有理由 this.word 等在 ngOnInit() 中不可见。他们的private 性质只是一个编译时概念,对代码的工作方式没有影响。一定有其他我们没有看到的事情发生。顺便问一下,Comment 是在哪里定义的?就你的代码而言,这不太可能编译,如果你仍然运行它,当 components 初始化时,你会得到一个 ReferenceError
  • 评论在哪里定义?感谢您的提问,这实际上是一个错误。它应该是 CommentComponent 并且 CommentComponent 是一个组件。它解决了我的问题。但是,我仍然没有在类中看到变量 this.word
  • 我更新了代码

标签: angular angular2-directives ngoninit


【解决方案1】:

原因很简单,你只是混淆了typevalue的赋值。

现在你有:private word: "hello";

应该是:private word: string = "hello";

: 后输入类型,= 后输入默认值。

access_modificatior variable_name: type = default_value

【讨论】:

    【解决方案2】:
    private word: "hello";
    

    这定义了一个名为“word”的字段,其type是“hello”。 IE。它可以拥有的唯一有效值(未定义和 null 除外)是“hello”。它不会初始化该字段,因此它仍然是未定义的。如果你想要一个字符串类型的字段,初始化为“hello”,你需要

    private word = "hello";
    

    这是一个较短的形式(感谢类型推断)

    private word: string = "hello";
    

    同样的解释代表components

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 2015-03-19
      • 2012-05-26
      • 1970-01-01
      • 1970-01-01
      • 2019-06-01
      • 1970-01-01
      相关资源
      最近更新 更多