Why provider is not injecting a simple service on my component?

Viewed 42

I have a simple module that i create:

@NgModule({
  declarations: [
    PhoneValidationComponent,
    PhoneVerificationComponent,
    PhoneCodeConfirmationComponent
  ],
  imports: [
    CommonModule,
    SharedModule,
  ],
  exports:[
    PhoneValidationComponent
  ],
  providers:[
    PhoneValidationController
  ]
})

Simple right? When i see this documentation from angular it says:

https://angular.io/guide/dependency-injection

"At the NgModule level, using the providers field of the @NgModule decorator. In this scenario, the HeroService is available to all components, directives and pipes declared in this NgModule. For example:"

@NgModule({
  declarations: [HeroListComponent]
  providers: [HeroService]
})
class HeroListModule {}

But the behavior is not correct, when i go to the page that as the exported component PhoneValidationComponent, i get the famous exception:

NullInjectorError: R3InjectorError(AppModule)[PhoneValidationController -> PhoneValidationController -> PhoneValidationController]:

But when i put this service on component level it works:

@Component({
  selector: 'app-phone-validation',
  templateUrl: './phone-validation.component.html',
  styleUrls: ['./phone-validation.component.scss'],
  animations: [
    trigger('visibilityChanged', [
      state('shown', style({ opacity: 1 })),
      state('hidden', style({ opacity: 0 })),
      transition('shown => hidden', animate('600ms')),
      transition('hidden => shown', animate('300ms')),
    ])
  ],
  providers:[
    PhoneValidationController
  ]
})

This is the html from the component:

<div [@visibilityChanged]="session == 'phone-verification' ? 'shown' : 'hidden'" [ngStyle]="{display: session == 'phone-verification' ? 'block' : 'none'}">
  <app-phone-verification *ngIf="session == 'phone-verification'" (emitBack)="goBack($event)" (emitChangeSession)="changeSession($event)"></app-phone-verification>
</div>

<div [@visibilityChanged]="session == 'phone-code-confirmation' ? 'shown' : 'hidden'" [ngStyle]="{display: session == 'phone-code-confirmation' ? 'block' : 'none'}">
  <app-phone-code-confirmation *ngIf="session == 'phone-code-confirmation'" (emitBack)="goBack($event)" (emitChangeSession)="changeSession($event)"></app-phone-code-confirmation>
</div>

My service:

@Injectable()
export class PhoneValidationController {

  private user: UserRequest = null as any;
  private phone: string = null as any;

  constructor() {}

  get currentUser(): UserRequest {
    return this.user;
  }

  set currentUser(user: UserRequest) {
    this.user = user;
  }

  get currentPhone(): string {
    return this.phone;
  }

  set currentPhone(phone: string) {
    this.phone = phone;
  }

}

I can follow this approach on Component level with no problem, but i want to know why i getting this error if i make the Module approach?

0 Answers
Related