我有一个看起来像这样的 Angular 服务
@Component({})
@Inject(ChromeDataService)
@Injectable()
export class MainDataService {
}
当我运行 ng build --prod
时,出现此错误
ERROR in : No template specified for component MainDataService
我唯一的猜测是 Angular 服务不需要是一个组件?所以我删除了 @Component
注释,但后来我得到了这个:
ERROR in : Unexpected value 'MainDataService in /home/.../main.ts' declared by the module 'SharedModule in /home/.../src/app/shared.module.ts'. Please add a @Pipe/@Directive/@Component annotation.
呃,如何在 Angular5 中创建服务?
最佳答案
要正确使用 Angular 服务,您只需要injectable()
这是一个例子
@Injectable()
export class myService {
//some logic
}
然后在您的 app.module
或功能模块中,您将服务添加到 providers
数组中,并让 Angular DI 为您处理该服务。
@Component({
usual stuff with template, selector, css})
export class someComponent {
constructor(private myService: MyService){}
}
构造函数将告诉 Angular 自动神奇地注入(inject)您需要的服务。
关于javascript - 如何使用 Angular5 声明服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48255864/