How to fix issues with property does not exist on type?

Viewed 46

I am new to angular so I was following a tutorial and have the following code:

  //Fetching users

  getUsers(size: number =10): Observable<any>{

    return this.http.get<any>(`${this.apiUrl}/?results=${size}`);

   }

The above code is for a component called user.services, this functiontries getting a api response, to use this method on another component I have the following:

export class UsersComponent implements OnInit {

  constructor(private userService: UserService) {  }

  ngOnInit(): void {
    
      this.userService.getUsers(10).subscribe(
        (results: any) => {
          console.log(results);
        }
      );


  }
}

Since I am injecting the userService on the constructor of the users.components.ts file I don't understand why I get the error saying Property 'getUsers' does not exist on type 'UserService'

I am able to see that VSCODE also sees the function definition

enter image description here

what could be the issue for this?

1 Answers

I think its due to not providing the service, you can do this in two ways

  1. adding the providedIn in the injector decorator! which makes it available throughout the angular project! if you give 'root'

ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root', // <- changed here
})
export class TestService {
  constructor() {}

  test() {
    console.log('hello!');
  }
}

forked stackblitz

  1. You can add it to the providers array of the respective module

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { TestService } from './test.service';

@NgModule({
  imports: [BrowserModule, FormsModule],
  declarations: [AppComponent, HelloComponent],
  bootstrap: [AppComponent],
  providers: [TestService],
})
export class AppModule {}

forked stackblitz

Related