zoukankan      html  css  js  c++  java
  • [Angular] Component's dependency injection

    An Angular service registered on the NgModule is globally visible on the entire application. Moreover it is a singleton instance, so every component that requires it via its constructor, will get the same instance. However this is not always the desired behavior.

    Rather you may like to get a fresh instance of a given service every time a component requests it. This is especially powerful for caching scenarios for instance. In this lesson we will learn how to achieve such behavior with Angular’s hierarchical dependency injector.

    It menas that, when you provide dependency injection for a component, it comes and goes with Component, which also mean, everytime component is renewed, the service provides init value, the old value will lose.

    @Component({
      selector: 'app-child',
      template: `
      <h3>Child component</h3>
      <pre>{{ personService.getPerson() | json }}</pre>
    
      <app-person-edit></app-person-edit>
      `,
      providers: [PersonService]
    })
    import { Injectable } from '@angular/core';
    
    @Injectable()
    export class PersonService {
      name = 'Joe';
    
      getPerson() {
        return {
          name: this.name,
          age: 23
        };
      }
    
      setPersonName(value) {
        this.name = value;
      }
    }

    So everytime the component's will get serivce name as 'Joe'.

  • 相关阅读:
    java几种数据的默认扩容机制
    web.xml配置详解
    Bootstrap文件上传组件
    JAVA四则运算算法
    Oracle 和 mysql 的批量操作Sql语句 的区别
    JAVA使用ItextPDF
    c# 状态机实现
    c++11模拟boost元占位符placeholder
    vs2012 函数参数内存对齐引发编译错误
    windows下matplotlib编译安装备忘
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8853447.html
Copyright © 2011-2022 走看看