0

When I inject UserService then component it doesn't appear When I remove service from component then component works fine

providers in @NgModule

providers: [
    UserService,
    {
      provide:AuthServiceConfig,
      useFactory: getAuthServiceConfigs
    }
  ],

Service Code

@Injectable()
export class UserService {
    API_URL = environment.apiUrl;

    constructor(private http: HttpClient) { }

    getAll() {
        return this.http.get<User[]>(this.API_URL+"getAllUsers");
    }
}

Component Code

export class UserRegistrationComponent implements OnInit {

  registerForm: FormGroup;
  submitted = false;
  newUser;
  userService: UserService;
   constructor(
        userService: UserService        
        ) 
       {
        config.backdrop = 'static';
        config.keyboard = false;
        this.userService=userService;
       }

  ngOnInit() {
      this.registerForm = this.formBuilder.group({
          emailId: ['', Validators.required],
          firstName: ['', Validators.required],
          lastName: ['', Validators.required],
          password: ['', [Validators.required, Validators.minLength(8)]]
      });
  }
}
Kalamarico
  • 5,466
  • 22
  • 53
  • 70
  • 2
    Hello and welcome! Can you please add more information? Are there errors in your console, IDE, or when you run a prod build? –  Mar 29 '19 at 16:48
  • Why invente doing things when you can find the right way everywhere? Why do you declare userService? Why a , in providers: [ UserService, { – Vega Mar 29 '19 at 17:43
  • Possible duplicate of [Angular service call function in component](https://stackoverflow.com/questions/36309837/angular-service-call-function-in-component) – Bhagwat Tupe Mar 29 '19 at 18:35

2 Answers2

0
export class UserRegistrationComponent implements OnInit {

  registerForm: FormGroup;
  submitted = false;
  newUser;
  // userService: UserService; remove this line
   constructor(
        userService: UserService        
        ) 
       {
        config.backdrop = 'static';
        config.keyboard = false;
       // this.userService=userService; remove this line
       }

  ngOnInit() {
      this.registerForm = this.formBuilder.group({
          emailId: ['', Validators.required],
          firstName: ['', Validators.required],
          lastName: ['', Validators.required],
          password: ['', [Validators.required, Validators.minLength(8)]]
      });
  }
}

if you remove the commented lines and then try, it should work. when you are having a parameter in constructor it automatically creates a variable for that class so you can use it like this.userService.getAll()

Barkha
  • 702
  • 3
  • 8
0

u get an instace of your service in your constructor like this:

constructor(private userService: UserService){}

and then you can use it like this:

this.userService.getAll()
RadekF
  • 476
  • 5
  • 10