未定义的错误Angular 2类

时间:2016-08-10 19:14:21

标签: javascript angular typescript

我不知道为什么会出现未定义的错误。这是我收到的错误消息:" TypeError:无法设置属性' state'未定义"

这是我的代码:

export class MobileMenuComponent implements OnInit {

menu: any;

constructor() { 


}

ngOnInit() { 

    this.menu.state = 'inactive';

    this.menu.togglemenu = function() {

        if (this.menu.state === 'inactive'){

            this.menu.state = 'active';

        }

        else {

            this.menu.state = 'inactive';

        }

    }

}


}

2 个答案:

答案 0 :(得分:1)

在构造函数中将this.menu定义为空对象,它将起作用。

答案 1 :(得分:1)

private async void _timer_Tick(object sender, object e) { DhtReading reading = new DhtReading(); int val = this.TotalAttempts; this.TotalAttempts++; reading = await _dht.GetReadingAsync().AsTask(); _retryCount.Add(reading.RetryCount); this.OnPropertyChanged(nameof(AverageRetriesDisplay)); this.OnPropertyChanged(nameof(TotalAttempts)); this.OnPropertyChanged(nameof(PercentSuccess)); if (reading.IsValid) { this.TotalSuccess++; this.Temperature = Convert.ToSingle(reading.Temperature); this.Humidity = Convert.ToSingle(reading.Humidity); this.LastUpdated = DateTimeOffset.Now; this.OnPropertyChanged(nameof(SuccessRate)); //Inserir aqui o método de gravação de arquivo. StreamWriter SW; SW = File.AppendText(@"Arquivo.txt"); SW.WriteLine("Evento Gerado em: " + DateTime.Now.ToString() + Humidity + Temperature + "\n\r"); SW.Close(); } } 函数内的

this - 用于函数本身,它不包含菜单成员。你应该使用内部togglemenu内部函数。像这样:

this