angular call service from component code example
Example 1: angular create a service
>>> ng generate service service_name
or
>>> ng generate service /folder-name/service-name
Example 2: calling angular component method in service
// -------------------------------------------------------------------------------------
// codes for component
import { JustAService} from '../justAService.service';
@Component({
selector: 'app-cute-little',
templateUrl: './cute-little.component.html',
styleUrls: ['./cute-little.component.css']
})
export class CuteLittleComponent implements OnInit {
s: JustAService;
a: number = 10;
constructor(theService: JustAService) {
this.s = theService;
}
ngOnInit() {
this.s.onSomethingHappended(this.doThis.bind(this));
}
doThis() {
this.a++;
console.log('yuppiiiii, ', this.a);
}
}
// -------------------------------------------------------------------------------------
// codes for service
@Injectable({
providedIn: 'root'
})
export class JustAService {
private myFunc: () => void;
onSomethingHappended(fn: () => void) {
this.myFunc = fn;
// from now on, call myFunc wherever you want inside this service
}
}
Example 3: angular import service
import { <service name>Service } from '../<service path>';
Example 4: angular how to use service in class
import { <service name>Service } from '../<service path>';
you can inject service in components constructor:
constructor(public anyService: Service){}