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

  • 相关阅读:
    MQTT介绍与使用
    SVN的搭建与使用
    Git版本控制之ubuntu搭建Git服务器
    蓝奏云的速度好快
    放大器的定义和主要参数
    模拟信号导论
    模拟电子电路学习笔记
    二极管单向导电的理解
    让蜂鸣器发声
    蜂鸣器的介绍
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8853447.html
Copyright © 2011-2022 走看看