javascript - 如何使用 Angular5 声明服务

标签 javascript angular angular5

我有一个看起来像这样的 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/

相关文章:

angular - nginx.conf 中的 try_files 不工作

html - 具有固定标题和可滚动 x-y 正文的 Css 表格

angular - 可扩展表行 td-datatable teradata Covalent

angular5 - TypeError : _this. flashMessagesService.show 不是函数

javascript - 如何使字符串不可附加?

Javascript - 自定义确认对话框 - 替换 JS 确认

angular - 模块解析失败 : . .. 意外标记。您可能需要适当的加载程序来处理此文件类型

javascript - 如何迭代 javascript 对象并对每个值运行函数

javascript - div 由 iframe 覆盖

Angular Material cdkDrag拖拽,目标元素如何使用?