Ts2304 cannot find the name 'OnInit'

I worked on a corner superhero training course. Everything works

If I close the cmd window where NPM is running, I re-open the CMD window and reissue the NPM START command. I get two errors

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'. 

I can solve this problem by removing

 Implements OnInit 

from both of these classes, start NPM and start adding them again (just CTL Z in the editor) make some changes, save. The application is recompiled and I am turned off.

I have 4 classes that implement this function. I studied them and can't figure out what makes 2 fail ...

I read the posts that reference TS2304, but this seems to be a generic message Function / Variable / Character not found ...

I do not know what to write. I am happy to publish any code.
Is this caused by errors in the modules it depends on (hero.ts)?

Here is one class that fails in this way. This is the hero-list.component.ts file (it is also called Heroes.component .. in different places of the demo / online examples ..)

 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; } }); } } 
+10
angular typescript
source share
3 answers

You need to import OnInit.

 import { Component, OnInit } from '@angular/core'; 
+31
source share

The manual does not mention that you need to add OnInit imports to the TypeScript file app.component.ts:

 import { Component, OnInit } from '@angular/core'; 
+6
source share

Just import OnInit

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

All Articles