【问题标题】:ts2304 cannot find name 'OnInit'ts2304 找不到名称“OnInit”
【发布时间】:2017-08-23 13:59:42
【问题描述】:

我已经完成了 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 启动 重新添加它们(只需在编辑器中使用 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; }
            });
    }
}

【问题讨论】:

  • 如果您拼错了“OnInit”,您将收到同样的错误。就我而言,我使用了“onInit”。希望它可以帮助某人。

标签: node.js angular typescript


【解决方案1】:

你必须导入 OnInit。

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

【讨论】:

    【解决方案2】:

    tutorial 没有提到需要将OnInit 的导入添加到TypeScript 文件app.component.ts

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

    【讨论】:

    • 在我的情况下,导入之前已经存在,正如您提到的正确的大写/小写,但我在问题中提到了这个错误。在 VS Code 终端中重新运行“ng start”没有帮助。然后我将这一行复制+粘贴到现有行上,重新运行“ng start”,它再次起作用。奇怪!
    【解决方案3】:

    只需导入 OnInit

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

    【讨论】:

    • 只有 18 个月后才有相同​​的答案......真是巧合!
    【解决方案4】:

    你必须在 ts 部分导入 OnInit。

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

    【讨论】:

      猜你喜欢
      • 2019-04-21
      • 1970-01-01
      • 2022-01-20
      • 2017-08-11
      • 1970-01-01
      • 2017-11-03
      • 2019-12-24
      • 1970-01-01
      • 2017-11-26
      相关资源
      最近更新 更多