美文网首页
Angular 依赖注入

Angular 依赖注入

作者: Messix_1102 | 来源:发表于2022-12-13 18:02 被阅读0次

    依赖注入 Demo

    • 使用@Injectable标记注入类
    import { Injectable } from '@angular/core';
    
    @Injectable({providedIn: 'root'})
    export class Logger {
      writeCount(count: number) {
        console.warn(count);
      }
    }
    
    • 在调用的地方通过构造函数注入
    import { Component } from '@angular/core';
    import { Logger } from '../logger.service';
    
    @Component({
      selector: 'hello-world-di',
      templateUrl: './hello-world-di.component.html'
    })
    export class HelloWorldDependencyInjectionComponent  {
      count = 0;
      // 构造函数注入 Logger
      constructor(private logger: Logger) { }
    
      onLogMe() {
        this.logger.writeCount(this.count);
        this.count++;
      }
    }
    

    相关文章

      网友评论

          本文标题:Angular 依赖注入

          本文链接:https://www.haomeiwen.com/subject/avrcqdtx.html