以下是在NgModule中注册服务的典型示例。import{NgModule}from'@angular/core';import{AuthService}from'./auth.service';@NgModule({providers:[AuthService],})classExampleModule{}上面的代码,由于提供和useClassattributes的值都是一样的,所以其实是简写(shorthand),完整的写法:import{NgModule}from'@angular/core';import{AuthService}from'./auth.service';@NgModule({providers:[{provide:AuthService,useClass:AuthService,},],})classExampleModule{}对象中的provide属性是我们正在注册的提供者的令牌。这意味着Angular可以使用useClass值来查找存储在AuthService令牌下的内容。Angular依赖注入为应用程序开发提供了许多好处。首先,我们现在可以拥有两个具有完全相同类名的提供者,Angular可以毫无问题地解析正确的服务。其次,我们还可以用不同的提供者覆盖现有的提供者,同时保持令牌不变。原始的AuthService类的实际情况:import{Injectable}from'@angular/core';import{Http}from'@angular/http';@Injectable()exportclassAuthService{constructor(privatehttp:Http){}authenticateUser(username:string,password:string):Observable{//返回true或falsereturnthis.http.post('/api/auth',{username,password});}getUsername():Observable{returnthis.http.post('/api/user');}}在LoginComponent里消费上描述Service类的代码:import{Component}from'@angular/core';import{AuthService}from'./auth.service';@Component({selector:'auth-login',template:``})exportclassLoginComponent{constructor(privateauthService:AuthService){}login(){this.authService.authenticateUser('toddmotto','straightouttacompton').subscribe((status:boolean)=>{//如果用户已经登录则做一些事情});}}在UserInfoComponent里使用这个服务类:@Component({selector:'user-info',template:`你是{{username}}!
`})classUserInfoComponentimplementsOnInit{username:string;构造函数(私有authService:AuthService){}ngOnInit(){this.authService.getUsername().subscribe((用户名:字符串)=>this.username=username);}}将两个组件类和一个服务类封装到一个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],})exportclassAuthModule{}可能还有其他组件使用同样的AuthService现在假设有一个新的需求,需要我们的Login认证方式,改成一个用Facebook登录用户的库。最愚蠢的方法是遍历每个组件实现并更改所有导入以指向这个新提供者,但我们可以利用依赖注入并轻松覆盖我们的AuthService以使用FacebookAuthService:import{NgModule}from'@angular/core';//完全由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,},],})exportclassAuthModule{}上面的例子用不同的值替换了useClass属性。这样,我们就可以在应用程序的任何地方使用AuthService——无需进一步更改。这是因为Angular使用AuthService作为令牌来搜索我们的提供者。因为我们用新类FacebookAuthService替换了它,所以我们所有的组件都将使用它。