Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an injected angular service as a dependency within a static method

I am trying to use a injected dependency within a static method and of course the injected dependency is instance-scoped and can't be used within the static method.

Here is my class:

@Injectable()
export class PasswordValidationService {

  constructor(private userAccountService:UserAccountService) {
  }

  static passwordValidator(control:AbstractControl) {
    return control
      .valueChanges
      .debounceTime(400)
      .switchMap(()=> this.userAccountService.checkCurrentPassword(control.value))
      .map(res=> {
          if (res.json() === true) {
            return null;
          }
          else {
            return {invalid: true};
          }
        }
      );
  }

}

My question is what is the best practice in order to use the UserAccountService (dependency) within a static method?

edit: I redesigned my app towards using instance methods instead of static methods as follows:

Here is the validator:

import {Injectable} from "@angular/core";
import {UserAccountService} from "../../useraccount/useraccount.service";
import {AbstractControl} from "@angular/common";
import {Observable} from "rxjs/Observable";


@Injectable()
export class PasswordValidationService {

  constructor(private userAccountService:UserAccountService) {
  }

  passwordValidator(control:AbstractControl):Observable<any> {
    let validationResult = this.userAccountService.checkCurrentPassword(control.value)
      .map(res=> {
          if (res.json() === true) {
            return null;
          }
          else {
            return {invalid: true};
          }
        }
      );

    return validationResult;
  }

}

Here is the component using the validator:

constructor(private router:Router,
              private formBuilder:FormBuilder,
              private stylingService:StylingService,
              private sessionService:SessionService,
              private passwordValidationService:PasswordValidationService) {
  }

  ngOnInit() {
    this.signinForm = this.formBuilder.group({
      credentials: this.formBuilder.group({
        username: [this.credentials.username, Validators.required],
        password: [this.credentials.password, [Validators.required, this.passwordValidationService.passwordValidator]]
      })
    });
  }

Here is the error message I get:

browser_adapter.ts:82 TypeError: Cannot read property 'userAccountService' of undefined
    at PasswordValidationService.passwordValidator (http://localhost:8080/app/shared/services/password-validation.service.js:18:36)
    at eval (http://localhost:8080/vendor/@angular/forms/src/validators.js:137:49)
    at Array.map (native)
    at _executeValidators (http://localhost:8080/vendor/@angular/forms/src/validators.js:137:23)
    at FormControl.eval [as validator] (http://localhost:8080/vendor/@angular/forms/src/validators.js:116:33)
    at FormControl.AbstractControl._runValidator (http://localhost:8080/vendor/@angular/forms/src/model.js:178:56)
    at FormControl.AbstractControl.updateValueAndValidity (http://localhost:8080/vendor/@angular/forms/src/model.js:164:29)
    at new FormControl (http://localhost:8080/vendor/@angular/forms/src/model.js:304:14)
    at FormBuilder.control (http://localhost:8080/vendor/@angular/forms/src/form_builder.js:36:16)
    at FormBuilder._createControl (http://localhost:8080/vendor/@angular/forms/src/form_builder.js:68:25)
like image 678
balteo Avatar asked Jul 19 '16 11:07

balteo


People also ask

Can you dependency inject a static class?

You can use dependency injection in a static class using method or property injection. However, you cannot use constructor injection in a static class because the constructor of a static class cannot accept any parameters.

Which components can be injected as a dependency in Angular?

The "Application Module" can be injected as a dependency in AngularJS.

What is the use of dependency injection in Angular?

Dependency injection, or DI, is one of the fundamental concepts in Angular. DI is wired into the Angular framework and allows classes with Angular decorators, such as Components, Directives, Pipes, and Injectables, to configure dependencies that they need.

What is injectable () in Angular service?

The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency. Likewise, the @Injectable() decorator indicates that a component, class, pipe, or NgModule has a dependency on a service. The injector is the main mechanism.


1 Answers

Either don't make the method static or forward from an instance method

export class PasswordValidationService {

  constructor(private userAccountService:UserAccountService) {
  }

  validate(control:AbstractControl) {
    return PasswordValidationService.passwordValidator(control);
  }

  static passwordValidator(control:AbstractControl) {
    ...
  }
}
like image 193
Günter Zöchbauer Avatar answered Sep 26 '22 00:09

Günter Zöchbauer