[英]Angular 7 Service providedIn: 'root'
I'm very new to angular development so please forgive me if this is a very basic question 我对角度开发很新,所以如果这是一个非常基本的问题,请原谅我
But I have a cart service which I have at the moment simply has a simple console log function 但我有一个购物车服务,我目前只有一个简单的控制台日志功能
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class CartService { constructor( ) {} public addItem() { console.log('Hello'); } }
and basically I cannot figure out how to use this service within a NG Module that I have installed , I have successfully used it in other components via the constructor but the ngmodule doesn't have this? 基本上我无法弄清楚如何在我安装的NG模块中使用此服务,我已成功通过构造函数在其他组件中使用它,但ngmodule没有这个?
I get the fact that it's a singleton at the app-module level by using the providedIn: 'root' tag added in angular 6 通过使用在角度6中添加的providedIn:'root'标签,我得到了它在app-module级别的单例
but just can't figure out how to call cartService.addItem()? 但只是无法弄清楚如何调用cartService.addItem()?
Thanks if anyone can help! 谢谢,如果有人可以帮助!
You can use Dependency Injection like this to call the service 您可以像这样使用依赖注入来调用服务
export class AppComponent {
constructor(private cartService: CartService) {
}
doSomething() {
this.cartService.addItem();
}
}
Below is the sample code of how to use service in component: 以下是如何在组件中使用服务的示例代码:
Component.ts Component.ts
import { Component, OnInit} from '@angular/core';
import { yourSeerviceName } from "PATH_TO_SERVICE";
@Component({
selector: 'app-dummy',
styleUrls: ['dummy.component.sass'],
templateUrl: 'dummy.component.html'
})
export class yourComponent implements OnInit {
// you can provide any name for variable it's upto you
constructor(private dummyService:yourSeerviceName) {
}
//access the method in you'r service by performing below action.
this.dummyService.yourMethod();
}
If you created a new module, you need to introduce the service to your module, by going to the .module.ts
file and adding your service to the providers
array. 如果您创建了一个新模块,则需要将该服务引入模块,方法是转到
.module.ts
文件并将服务添加到providers
数组中。 It will be something like: 它将是这样的:
providers: [
CartService
],
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.