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

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

在 NgModule 里通過(guò)依賴注入的方式注冊(cè)服務(wù)實(shí)例

作者:汪子熙 更新時(shí)間: 2022-07-19 編程語(yǔ)言

下面是在 NgModule 中注冊(cè)一個(gè) service 的典型例子。

import { NgModule } from '@angular/core';

import { AuthService } from './auth.service';

@NgModule({
  providers: [AuthService],
})
class ExampleModule {}

上面的代碼,因?yàn)?provide 和 useClass 屬性值都相同,所以其實(shí)是簡(jiǎn)寫形式(shorthand),完整的寫法:

import { NgModule } from '@angular/core';

import { AuthService } from './auth.service';

@NgModule({
  providers: [
    {
      provide: AuthService,
      useClass: AuthService,
    },
  ],
})
class ExampleModule {}

對(duì)象中的 provide 屬性是我們正在注冊(cè)的提供者的令牌。 這意味著 Angular 可以使用 useClass 值查找 AuthService 令牌下存儲(chǔ)的內(nèi)容。

Angular 依賴注入為應(yīng)用程序開發(fā)提供了許多好處。 首先,我們現(xiàn)在可以擁有兩個(gè)具有完全相同類名的 providers,Angular 在解析正確的服務(wù)時(shí)不會(huì)有任何問(wèn)題。 其次,我們還可以使用不同的提供者覆蓋現(xiàn)有提供者,同時(shí)保持令牌相同。

原始的 AuthService 類的實(shí)現(xiàn):

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 里消費(fèi)上述 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 里使用這個(gè) 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);
  }

}

把兩個(gè) Component Class 和一個(gè) Service class 封裝到一個(gè) 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。 現(xiàn)在假設(shè)有一個(gè)新的需求,需要將我們的登錄身份驗(yàn)證方式,更改為一個(gè)使用 Facebook 登錄用戶的庫(kù)。

最笨的辦法是遍歷每一個(gè)組件實(shí)現(xiàn),并更改所有導(dǎo)入以指向這個(gè)新的提供者,但是我們可以利用依賴注入,輕松覆蓋我們的 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 屬性。 這樣,我們可以在我們的應(yīng)用程序中的任何地方使用 AuthService - 而無(wú)需進(jìn)行進(jìn)一步的更改。

這是因?yàn)?Angular 使用 AuthService 作為令牌來(lái)搜索我們的提供者。 由于我們已將其替換為新類 FacebookAuthService,因此我們所有的組件都將使用它。

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

欄目分類
最近更新