当前位置:网站首页>在 NgModule 里通过依赖注入的方式注册服务实例
在 NgModule 里通过依赖注入的方式注册服务实例
2022-07-25 16:21:00 【Jerry Wang】
下面是在 NgModule 中注册一个 service 的典型例子。
import { NgModule } from '@angular/core';
import { AuthService } from './auth.service';
@NgModule({
providers: [AuthService],
})
class ExampleModule {}上面的代码,因为 provide 和 useClass 属性值都相同,所以其实是简写形式(shorthand),完整的写法:
import { NgModule } from '@angular/core';
import { AuthService } from './auth.service';
@NgModule({
providers: [
{
provide: AuthService,
useClass: AuthService,
},
],
})
class ExampleModule {}对象中的 provide 属性是我们正在注册的提供者的令牌。 这意味着 Angular 可以使用 useClass 值查找 AuthService 令牌下存储的内容。
Angular 依赖注入为应用程序开发提供了许多好处。 首先,我们现在可以拥有两个具有完全相同类名的 providers,Angular 在解析正确的服务时不会有任何问题。 其次,我们还可以使用不同的提供者覆盖现有提供者,同时保持令牌相同。
原始的 AuthService 类的实现:
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');
}
}在 LoginComponent 里消费上述 Service 类的代码:
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
});
}
}在 UserInfoComponent 里使用这个 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);
}
}把两个 Component Class 和一个 Service class 封装到一个 NgModule 里:
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 {}也可能存在其他组件使用相同的 AuthService。 现在假设有一个新的需求,需要将我们的登录身份验证方式,更改为一个使用 Facebook 登录用户的库。
最笨的办法是遍历每一个组件实现,并更改所有导入以指向这个新的提供者,但是我们可以利用依赖注入,轻松覆盖我们的 AuthService 以使用 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 {}上面的例子用不同的值替换了 useClass 属性。 这样,我们可以在我们的应用程序中的任何地方使用 AuthService - 而无需进行进一步的更改。
这是因为 Angular 使用 AuthService 作为令牌来搜索我们的提供者。 由于我们已将其替换为新类 FacebookAuthService,因此我们所有的组件都将使用它。
边栏推荐
- 如何构建面向海量数据、高实时要求的企业级OLAP数据引擎?
- MySQL tutorial 68-as setting alias
- 没错,请求DNS服务器还可以使用UDP协议
- I interviewed 8 companies and got 5 offers in a week. Share my experience
- Upgrade esxi6.7.0 to 7.0u3f (updated on July 12, 2022)
- 食品安全丨无处不在的冷冻食品,你真的了解吗?
- 排他锁(EXclusive Lock)
- 狂神redis笔记12
- MySQL tutorial 65 data in MySQL operation table
- 01.一个更简单的方法来传递大量的props
猜你喜欢

2w字详解数据湖:概念、特征、架构与案例

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

Exploration of 6-wire SPI transmission mode
![[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
![[zeloengine] summary of pit filling of reflection system](/img/7a/c85ba66c5dd05908b2d784fab306a2.png)
[zeloengine] summary of pit filling of reflection system

一文理解分布式开发中的服务治理

Win11自带画图软件怎么显示标尺?

今天去 OPPO 面试,被问麻了
![Leetcode:528. select randomly according to the weight [ordinary random failure + prefix and dichotomy]](/img/fb/8178388f8c9ac80d95140378d24238.png)
Leetcode:528. select randomly according to the weight [ordinary random failure + prefix and dichotomy]
![[image denoising] image denoising based on bicube interpolation and sparse representation matlab source code](/img/39/716c62d6ca533a7e84704b2c55d072.png)
[image denoising] image denoising based on bicube interpolation and sparse representation matlab source code
随机推荐
伦敦银K线图的各种有用形态
MySQL implicit lock
MySQL isolation level transactions
Typescript learning 2 - Interface
MySQL table write lock
MySQL metadata lock (MDL)
pymongo保存dataframe格式的数据(insert_one, insert_many, 多线程保存)
Talk about how to use redis to realize distributed locks?
狂神redis笔记12
聊聊如何用 Redis 实现分布式锁?
Doget and dopost
PageHelper.startPage没有生效问题
leetcode:154. 寻找旋转排序数组中的最小值 II【关于旋转排序数组的中后定位二分法】
mysql意向锁
面试突击:为什么 TCP 需要 3 次握手?
Promise期约
MQTT X CLI 正式发布:强大易用的 MQTT 5.0 命令行工具
Release of v6.5.1/2/3 series of versions of Xingyun housekeeper: the ability of database OpenAPI continues to be strengthened
Use huggingface to quickly load pre training models and datasets in moment pool cloud
leetcode:6127. 优质数对的数目【位运算找规律 + 两数之和大于等于k + 二分】