An example of Angular dependency injection and injection principle single step debugging

Define an abstract service class:

export abstract class GreetingService {
    abstract greet(name: string): string;
 }

Define a concrete class to implement the abstract class:

import { Injectable } from '@angular/core';
import { GreetingService } from './greeting.service';

@Injectable({ providedIn: 'root'})
export class EnglishGreetingService extends GreetingService {
   greet(name: string): string {
      return 'Hello ' + name;
   }
   constructor(){
      super();
      console.log('English class created!');
   }
}

Use the annotation @Injectable to mark that this class can be injected into other components.

Parameter injection in the constructor:

Debugging the principle of dependency injection:

Use app Component factory to create Component instance:


Our service implementation class modified by Angular Injectable annotation has been successfully parsed and appeared in the implementation code of the Angular framework, stored through the token variable:

In the lView variable returned by the Angular framework method getLView, you can see the implementation code of App Component template:

An instance of the service implementation class is generated here:


To get more original articles by Jerry, please follow the public account "Wang Zixi":

Guess you like

Origin blog.csdn.net/i042416/article/details/108640353