Angular2 - OnInit未定义

Mih*_*šič 12 typescript angular

我正在尝试实现angular 2 onInit函数,但我在控制台中收到以下错误:

错误:ReferenceError:未定义OnInit(...)

有人可以指出我做错了什么吗?

这是我的组成部分:

import { Component, OnInit } from 'angular2/core';
import { ViewEncapsulation } from 'angular2/core';

@Component({
    selector: 'Landing',
    templateUrl: '/app/views/landing.html',
    styleUrls: ['../app/styles/landing.css'],
    encapsulation: ViewEncapsulation.None
})

export class LandingComponent implements OnInit {

    function checkOverflow() {
        var element = document.querySelector('.appContainer');
        if( (element.offsetHeight < element.scrollHeight) || (element.offsetWidth < element.scrollWidth)){
           // your element have overflow
          console.log('OVERFLOW!');
        }
        else{
          console.log('NO OVERFLOW');
        }
    }

    OnInit() {
        checkOverflow();
    }

}
Run Code Online (Sandbox Code Playgroud)

Pan*_*kar 17

使用singleimport而不是两个import语句.还可以使用@之前@angular/core,如果您使用的是rc(发布候选)版

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
Run Code Online (Sandbox Code Playgroud)

您应该ngOnInit在组件类implements OnInit类中实现方法

ngOnInit() {
    this.checkOverflow();
}
Run Code Online (Sandbox Code Playgroud)

另外,请不要使用function您当前在打字稿文件中使用的方式,将其转换为checkOverflow(){ ... }格式然后再调用它this.checkOverflow()