博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Angular] Component's dependency injection
阅读量:4972 次
发布时间:2019-06-12

本文共 1234 字,大约阅读时间需要 4 分钟。

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: `  

Child component

{
{ personService.getPerson() | json }}
`, 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'.

 

转载于:https://www.cnblogs.com/Answer1215/p/8853447.html

你可能感兴趣的文章
对Haskell这门语言的基本认识
查看>>
mysql 安装补充
查看>>
大学里如何学习 ?
查看>>
Oracle命令类别
查看>>
js面试题:关于数组去重的四种方法总结
查看>>
Linux内核分析(三)----初识linux内存管理子系统
查看>>
stc12c5a60s2驱动TEA5767收音机模块硬件调试总结
查看>>
vue中提示$index is not defined
查看>>
Java中对List集合内的元素进行顺序、倒序、随机排序的示例代码
查看>>
css选择器
查看>>
看懂下面C++代码才说你理解了C++多态虚函数!
查看>>
ASP.NET上传下载文件
查看>>
Galaxy Nexus 全屏显示-隐藏Navigation Bar
查看>>
Spring中使用Velocity模板
查看>>
上周热点回顾(8.18-8.24)
查看>>
Feature toggle
查看>>
day02
查看>>
gvim 配置Pydiction
查看>>
Linux安装指定mysql版本
查看>>
分布式锁的三种实现方式
查看>>