当前位置:网站首页>Register service instances in ngmodule through dependency injection
Register service instances in ngmodule through dependency injection
2022-07-25 16:24:00 【Jerry Wang】
The following is the NgModule Register one service Typical example .
import { NgModule } from '@angular/core';
import { AuthService } from './auth.service';
@NgModule({
providers: [AuthService],
})
class ExampleModule {} The above code , because provide and useClass Property values are the same , So it's actually a short form (shorthand), The whole way of writing :
import { NgModule } from '@angular/core';
import { AuthService } from './auth.service';
@NgModule({
providers: [
{
provide: AuthService,
useClass: AuthService,
},
],
})
class ExampleModule {}Object provide Attribute is the token of the provider we are registering . It means Angular have access to useClass Value search AuthService Contents stored under the token .
Angular Dependency injection provides many benefits for application development . First , We can now have two with exactly the same class name providers,Angular There will be no problem parsing the correct service . secondly , We can also overwrite existing providers with different providers , Keep the token the same .
The original AuthService The realization of the class :
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable()
export class AuthService {
constructor(private http: Http) {}
authenticateUser(username: string, password: string): Observable<boolean> {
// returns true or false
return this.http.post('/api/auth', { username, password });
}
getUsername(): Observable<string> {
return this.http.post('/api/user');
}
}stay LoginComponent Consumption above Service Class code :
import { Component } from '@angular/core';
import { AuthService } from './auth.service';
@Component({
selector: 'auth-login',
template: `
<button>
Login
</button>
`
})
export class LoginComponent {
constructor(private authService: AuthService) {}
login() {
this.authService
.authenticateUser('toddmotto', 'straightouttacompton')
.subscribe((status: boolean) => {
// do something if the user has logged in
});
}
}stay UserInfoComponent Use this in Service class:
@Component({
selector: 'user-info',
template: `
<div>
You are {{ username }}!
</div>
`
})
class UserInfoComponent implements OnInit {
username: string;
constructor(private authService: AuthService) {}
ngOnInit() {
this.authService
.getUsername()
.subscribe((username: string) => this.username = username);
}
}Take two. Component Class And a Service class Package into a NgModule in :
import { NgModule } from '@angular/core';
import { AuthService } from './auth.service';
import { LoginComponent } from './login.component';
import { UserInfoComponent } from './user-info.component';
@NgModule({
declarations: [LoginComponent, UserInfoComponent],
providers: [AuthService],
})
export class AuthModule {}There may also be other components that use the same AuthService. Now suppose there is a new requirement , We need to change our login authentication method , Change to a use Facebook Log in to the user's Library .
The dumbest way is to traverse every component implementation , And change all imports to point to the new provider , But we can use dependency injection , Easily cover our AuthService To use the FacebookAuthService:
import { NgModule } from '@angular/core';
// totally made up
import { FacebookAuthService } from '@facebook/angular';
import { AuthService } from './auth.service';
import { LoginComponent } from './login.component';
import { UserInfoComponent } from './user-info.component';
@NgModule({
declarations: [LoginComponent, UserInfoComponent],
providers: [
{
provide: AuthService,
useClass: FacebookAuthService,
},
],
})
export class AuthModule {}The above example replaces useClass attribute . such , We can use it anywhere in our application AuthService - Without further changes .
This is because Angular Use AuthService Search our provider as a token . Because we have replaced it with a new class FacebookAuthService, So all our components will use it .
边栏推荐
- 解决Win10磁盘占用100%
- [image hiding] digital image watermarking method technology based on hybrid dwt-hd-svd with matlab code
- tkinter模块高级操作(一)—— 透明按钮、透明文本框、自定义按钮及自定义文本框
- Communication between processes (pipeline details)
- Verifiable random function VRF
- ILSSI认证|六西格玛DMAIC的历程
- Fastadmin TP installation uses Baidu rich text editor ueeditor
- How to build an enterprise level OLAP data engine for massive data and high real-time requirements?
- MYSQL导入sqllite表格的两种方法
- MySQL显式锁
猜你喜欢

0x80131500打不开微软商店的解决办法

论文笔记:Highly accurate protein structure prediction with AlphaFold (AlphaFold 2 & appendix)

easyui修改以及datagrid dialog form控件使用

从业务需求出发,开启IDC高效运维之路

Test Driven Development (TDD) online practice room | classes open on September 17

聊聊如何用 Redis 实现分布式锁?

Product upgrade observation station in June

今天睡眠质量记录84分

Various useful forms of London Silver K-line chart
![[fault diagnosis] bearing fault diagnosis based on Bayesian optimization support vector machine with matlab code](/img/9e/138e4b160fa9bd6486fac44a788d09.png)
[fault diagnosis] bearing fault diagnosis based on Bayesian optimization support vector machine with matlab code
随机推荐
Test Driven Development (TDD) online practice room | classes open on September 17
MySQL intent lock
02. Limit the parameter props to a list of types
Sum arrays with recursion
mysql 隔离级别事务
The presentation logic of mail sending and receiving inbox outbox and reply to the problem of broken chain
Win11桌面切换快捷键是什么?Win11快速切换桌面的方法
测试框架-unittest-测试套件、结果输出到文件
[image denoising] image denoising based on bicube interpolation and sparse representation matlab source code
Food safety - do you really understand the ubiquitous frozen food?
Fastadmin TP installation uses Baidu rich text editor ueeditor
Google Earth Engine——全球建筑物GlobalMLBuildingFootprints矢量集合下载
Baidu rich text editor ueeditor single image upload cross domain
Mysql读写锁
Leetcode:6127. Number of high-quality number pairs [bit operation finding rules + the sum of two numbers is greater than or equal to K + dichotomy]
一文理解分布式开发中的服务治理
How does win11's own drawing software display the ruler?
[wechat applet] detailed explanation of applet host environment
如何安装govendor并打开项目
leetcode:528. 按权重随机选择【普通随机失效 + 要用前缀和二分】