ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

在 NgModule 里通过依赖注入的方式注册服务实例

2022-07-19 23:06:55  阅读:184  来源: 互联网

标签:auth angular 实例 注册 import NgModule AuthService class


下面是在 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,因此我们所有的组件都将使用它。

标签:auth,angular,实例,注册,import,NgModule,AuthService,class
来源: https://www.cnblogs.com/sap-jerry/p/16496155.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有