angular - 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 ?
解决方案
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.
推荐阅读
- java - Spring Role Base 身份验证微服务应用程序
- java - java.sql.SQLNonTransientConnectionException:需要 CLIENT_PLUGIN_AUTH
- php - 在laravel中将数字四舍五入到最接近的9
- kotlin - 清单未达到活动
- java - 线程安全问题 - 没有得到预期的答案
- android - 使用 TextField Flutter 选择购物车数量
- python - 如何在 tkinter 中根据不同大小的计算机屏幕放置小部件
- python - BeautifulSoup 没有读取相同的 HTML 源代码
- java - 选择 FromDate 时出错
- angular - Jasmine 单元测试用例中的模拟窗口对象