如何在Angular 5中使用@Injectable includedIn根

时间:2018-07-26 15:34:36

标签: angular

当我使用

@Injectable({
    providedIn: 'root'
})

这些行一直用红色加下划线,并显示以下消息:期望参数为0,但得到1。有关操作的任何想法。

我一直在https://angular.io/tutorial/toh-pt4#injectable-services处关注文档 这是代码:

import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';
import { MessageService } from './message.service';

@Injectable({
  providedIn: 'root',
})
export class HeroService {

//Modify the constructor with a parameter that declares a private 
messageService property. 
 // Angular will inject the singleton MessageService into that property when 
it creates 
  // the HeroService.
 constructor(private messageService: MessageService) { }

getHeroes(): Observable<Hero[]> {
// TODO: send the message _after_ fetching the heroes
this.messageService.add('HeroService: fetched heroes');
return of(HEROES);
}
}

1 个答案:

答案 0 :(得分:2)

我认为此功能是Angular 6中引入的,因此您必须删除它,而在组件的模块中提供服务:

@NgModule
....
providers: [MyService]