codaholic
codaholic

Reputation: 335

Instance of the injected service is undefined in Angular 12

Angular Version : 12.0.1

I have created a service for a component, My requirement is to use the service only with this component for now. When I inject the service in the component and try to access its instance it is undefined. For the very first time in the ngOnInit, it is acccessible, but undefined elsewhere.

Relevant code in the component :

@Component({
  selector: 'app-component',
  templateUrl: './app-component.component.html',
  styleUrls: ['./app-component.component.scss'],
  providers : [MyService]
})
export class AppComponent implements OnInit {
  ...some declarations and initializations
  constructor(private myService: MyService) {}

  ngOnInit(): void {
    this.myObservable$ = this.myService?.getSomething('/');
  }


  functionCalledFromTemplaceButtonClick(item : any){

   // The service is undefined here
   return this.myService.getSomething(item);
  }


}

Relevant code from the service:

@Injectable({
  providedIn: 'root',
})
export class MyService {
  constructor(
    private httpClient: HttpClient,
  ) {}

  getSomething(item: any) {
   // Makes an api call here
  }
}

I have provided the Service - MyService in the module as well.

None of the existing issues helped, Kindly request for some help.

Upvotes: 4

Views: 2977

Answers (1)

codaholic
codaholic

Reputation: 335

I removed the method i had and replace it with a arrow function and declared and defined at the top such as below :

public functionCalledFromTemplaceButtonClick =(item : any) =>{

   // The service has the context here
   return this.myService.getSomething(item);
  }

Upvotes: 4

Related Questions