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?
I get the fact that it's a singleton at the app-module level by using the providedIn: 'root' tag added in angular 6
but just can't figure out how to call 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
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. It will be something like:
providers: [
CartService
],
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.