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'.

  • 相关阅读:
    整站爬虫命令
    小故事集锦
    中国最经典广告语大全
    常用的正则表达式
    特殊成员方法
    使用super函数----增量重写普通方法和构造方法
    重写普通方法和构造方法------原类的方法会被覆盖
    Python的数据类型与数据结构
    类和对象
    生产者-消费者问题与quene模块
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8853447.html
Copyright © 2011-2022 走看看