日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

在 NgModule 里通過依賴注入的方式注冊服務實例

作者:汪子熙 更新時間: 2022-07-19 編程語言

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

原文鏈接:https://blog.csdn.net/i042416/article/details/125858315

欄目分類
最近更新