当前位置:网站首页>Register service instances in ngmodule through dependency injection

Register service instances in ngmodule through dependency injection

2022-07-25 16:24:00 Jerry Wang

The following is the NgModule Register one service Typical example .

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

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

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

The above code , because provide and useClass Property values are the same , So it's actually a short form (shorthand), The whole way of writing :

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

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

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

Object provide Attribute is the token of the provider we are registering . It means Angular have access to useClass Value search AuthService Contents stored under the token .

Angular Dependency injection provides many benefits for application development . First , We can now have two with exactly the same class name providers,Angular There will be no problem parsing the correct service . secondly , We can also overwrite existing providers with different providers , Keep the token the same .

The original AuthService The realization of the class :

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');
  }

}

stay LoginComponent Consumption above Service Class code :

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
      });
  }

}

stay UserInfoComponent Use this in 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);
  }

}

Take two. Component Class And a Service class Package into a NgModule in :

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 {}

There may also be other components that use the same AuthService. Now suppose there is a new requirement , We need to change our login authentication method , Change to a use Facebook Log in to the user's Library .

The dumbest way is to traverse every component implementation , And change all imports to point to the new provider , But we can use dependency injection , Easily cover our AuthService To use the 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 {}

The above example replaces useClass attribute . such , We can use it anywhere in our application AuthService - Without further changes .

This is because Angular Use AuthService Search our provider as a token . Because we have replaced it with a new class FacebookAuthService, So all our components will use it .

原网站

版权声明
本文为[Jerry Wang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/206/202207251618571157.html