typescript Angular2 - OnInit 未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37257179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:29:11  来源:igfitidea点击:

Angular2 - OnInit is not defined

typescriptangular

提问by Miha ?u?ter?i?

I'm trying to implement the angular 2 onInit function but I get the following error in the console:

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

Error: ReferenceError: OnInit is not defined(...)

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

Can somebody point out what I'm doing wrong?

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

This is my component:

这是我的组件:

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

}

回答by Pankaj Parkar

Use singleimport instead of two import statements. Also use @before @angular/coreif you are using rc(release candidate) version

使用singleimport 而不是两个 import 语句。如果您使用(发布候选)版本,也可以使用@before@angular/corerc

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

You should implement ngOnInitmethod as you component class implements OnInitclass

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

ngOnInit() {
    this.checkOverflow();
}

Additionally don't use functionin the way you are currently using in typescript file, do convert it to checkOverflow(){ ... }format & then call it like this.checkOverflow()

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