ts2304找不到名称为'OnInit'的内容。

25

我已经完成了 Angular 超级英雄教程,一切正常。

如果我关闭正在运行 NPM 的 cmd 窗口,然后重新打开一个 CMD 窗口并重新发出 NPM START 命令,我会得到两个错误。

src/app/DashBoard.component.ts(12,44)  TS2304 : Cannot find name 'OnInit'.
src/app/hero-list.component.ts(16, 434)  TS2304 : Cannot find name 'OnInit'.
我可以通过移除

来解决这个问题。
Implements OnInit

从这两个类中,运行NPM start,重新添加它们(只需在编辑器中按CTL Z),进行一些更改,保存。应用程序重新编译,我就可以运行了。

我有4个实现此功能的类。我已经研究过它们,但无法弄清楚是什么导致了其中2个失败...

我阅读了帖子引用TS2304,但这似乎是一个通用的“找不到函数/变量/符号”的消息...

我不知道要发布什么。我很乐意发布任何代码。
这是由依赖于模块(hero.ts)的错误引起的吗?

这里是一个以这种方式失败的类。 这是hero-list.component.ts文件 (在演示/在线示例的不同点上,它也被命名为Heroes.component..)

import { Component } from '@angular/core';
import { Router } from '@angular/router';

import { Hero  } from './hero';
import { HeroService  } from './hero.service';

@Component({
  selector: 'hero-list',
  templateUrl: './hero-list.component.html' ,
  providers: [HeroService],
  styleUrls: [ './hero-list.component.css']
})



export class HeroListComponent implements OnInit   {

    heroes : Hero[];
    selectedHero: Hero;

    constructor(
        private router : Router ,
        private heroService: HeroService
        ) { }

    ngOnInit(): void {
        this.getHeroes();
    }

    onSelect(hero: Hero): void {
        this.selectedHero = hero;
    }

    getHeroes(): void {
        this.heroService.getHeroes().then(heroes => this.heroes = heroes);
    }

    gotoDetail() {
        this.router.navigate(['/detail', this.selectedHero.id]);
    }

    add(name: string): void {
        name = name.trim();
        if (!name) { return; }
        this.heroService.create(name)
            .then(hero => {
                this.heroes.push(hero);
                this.selectedHero = null;
            });
    }
    delete(hero: Hero): void {
        this.heroService
            .delete(hero.id)
            .then(() => {
                this.heroes = this.heroes.filter(h => h !== hero);
                if (this.selectedHero === hero) { this.selectedHero = null; }
            });
    }
}

2
如果你拼写 'OnInit' 写成了 'onInit',你将会得到相同的错误。在我的情况下,我使用了 'onInit'。希望能对某人有所帮助。 - Nithin Baby
2个回答

62

你需要导入OnInit。

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

13

这个教程没有提到你需要在TypeScript文件app.component.ts中添加导入OnInit的内容:

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

在我的情况下,像你提到的那样,导入语句大小写正确并且已经存在,但是我还是遇到了问题。在 VS Code 终端中重新运行 'ng start' 没有帮助。然后我将这一行代码完全复制粘贴到现有的代码上方,重新运行 'ng start',然后就可以正常工作了。真奇怪! - Matt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接