首页 > 解决方案 > Why we use @Injectable({ providedIn: 'root' }) to reach class?

问题描述

I have a custom class to create custom validator. to use that validator in FormGroup I do like this:

@Injectable({ providedIn: 'root' })
export class MatchPassword {

}

in another class

import { MatchPassword } from '../validators/match-password';

export class SignupComponent implements OnInit {
  authForm = new FormGroup(
    {
      username: new FormControl('')
    },
    {
      validators: [this.match.validate],
    }
  );

  constructor(private match: MatchPassword) {}

  ngOnInit(): void {}
}

why I dont use like

const object = new MatchPssword();

to create an instance ?

标签: angular

解决方案


You don't need to create an instance, you need to re-use an instance that your component depends on, and that the framework created at the startup.

You couldn't share information between components using new, instead, thanks to dependency injection, you can do something like this:

@Injectable({provideIn: 'root'})
export class MyService() {
  object: T = null;
  save(object: T) {
    this.object = object;
  }

  retrieve(): T {
    return this.object;
  }
}

And you can use save in a component and retrieve in another component, limiting the coupling.

Using new, instead, you would get two instances of MyService.object. In this case, services are very similar to singletons, but they're not singletons since they're managed by the framework and not by the developer.


推荐阅读