When working on my program, I encountered an issue where I am trying to create a service and declare a variable within the service. I then created a get() method in the service to print the variable by calling the service method from a component, but I keep getting undefined as the output. Why is this happening?
AppComponent.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
}
}
AppComponent.html
<app-comp1></app-comp1>
Comp1Component.ts
import { Component, OnInit } from '@angular/core';
import { AService } from 'src/app/services/a.service';
@Component({
selector: 'app-comp1',
templateUrl: './comp1.component.html',
styleUrls: ['./comp1.component.css']
})
export class Comp1Component implements OnInit {
constructor(private aService:AService) { }
ngOnInit() {
this.aService.getFunc1();
}
}
AService.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AService {
private a;
constructor() { }
public func1():void
{
this.a=11;
}
public getFunc1()
{
console.log(this.a);
}
}