Understanding Dependency Injection for angular

这篇具有很好参考价值的文章主要介绍了Understanding Dependency Injection for angular。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1. The  official doc link  for denpendency injection

Angularhttps://angular.io/guide/dependency-injection

Denpendency Injection,  or DI, is one of fundamental concepts for angular, DI is writed by angular framework and allows classes with  Angular decorators,  such as Components, directives, Piples and Injectables, to configure dependencies that they need.

 Two main roles exists in DI system: dependency consumer and dependency provider. 

2. @Injectable

An angular class or other definition that provides a  dependency using dependency injection mechanism. An injectable service class must be marked by @Injectable decorator, Other items, such as  constant values, can also be injectable. 

There has an option for @Injectable decorator ,which is "providedIn?".

Option Description
providedIn?

Determines which injectors will provide the injectable.

 It mainly has 5 value for diferent scenario:

providedIn?: Type<any> | 'root' | 'platform' | 'any' | null

But  "Type<any>" and "any"  are DEPRECATED

  • 'null' :  equivalent to  undefined. The injectable is not provided in any scope automatically and must be added to a providers array of an @NgModule, @Component, or @Directive.
  • 'root':  The application-level injector in most apps.
  • 'platform': A special singleton platform injector shared by all applications on the page.

The following example shows a service class is properly marked by @Injectable  so that a supporting service can be injected upon creation.

@Injectable()
class UsefulService {
}

@Injectable()
class NeedsService {
  constructor(public service: UsefulService) {}
}

const injector = Injector.create({
  providers:
      [{provide: NeedsService, deps: [UsefulService]}, {provide: UsefulService, deps: []}]
});
expect(injector.get(NeedsService).service instanceof UsefulService).toBe(true);

3. Providing dependency

A providing dependency must  be marked by @Injectable() decorator, let us see the @Injectable decorator.

The first step is to add the @Injectable decorator to show that the class can be injected:

@Injectable()
class HeroService {}

The next step is to make it available in the DI by providing it. A dependency can be provided in multiple places:

  •  At the component level, using the providers field of the @Component decorator. In this case the HeroService becomes  available to all instances of this component and other component and directives used in the template, for example:  
@Component({
  selector: 'hero-list',
  template: '...',
  providers: [HeroService]
})
class HeroListComponent {}

When you register a provider at the component level, you will get a new instance of the service witch each new  instance of that component.

  • At the application level, there has two ways to define a provider.  one realized by @NgModule in providers field.
@NgModule({
  declarations: [HeroListComponent]
  providers: [HeroService]
})
class HeroListModule {}

The other method is realized by @Injectable decorator,  we just need to fill the value 'root' in "provideIn" option:

@Injectable({
  providedIn: 'root'
})
class HeroService {}

note that this way's suitable for one instance in a project, but if you want to each component has a new instance,  the first way is a good choice. 

4. Injecting a dependency 

There has two ways to inject a dependency in angular, one is we can use constructor, the another option is to use inject method. The constructor can look like this:

@Component({ … })
class HeroListComponent {
  constructor(private service: HeroService) {}
}

use inject method:

@Component({ … })
class HeroListComponent {
  private service = inject(HeroService);
}

(类似于spring 三级缓存管理bean 的机制)When angular discvoer that a component depends on a service, it first check if the injector has any existing instance of that service, If a requested service instance doesn't yet exit, the injector creates one using the registered provider, and adds it to the injector before returning the service to Angular. 

When all requested services have been resolved and returned, Angular can call the component's constructor with those services as arguments.

 Understanding Dependency Injection for angular,vue-react-angular-web,angular.js,前端,javascript

5. Case

This is my hello component, I want to refer the another component: english

import {Component} from "@angular/core";



@Component({"template":"<div>I love studying</div>"})
export class StudyEnglishComponent{

   
   public vocabulary(){
      console.log("for the record, I have finished my vocabulary today!")
   }

}
import 'reflect-metadata'
import { Component } from "@angular/core";

import { StudyEnglishComponent} from "../study/study.english.component";

// @MyComponent({
//     "selector":'hello-word',
//     "template":'<div>hello word</div>',
// })
@Component({'selector':'hello-word',template:'<div class="hello" style="font:200px">hello world</div>',styleUrls:['./helloWord.component.css']})
export class HelloComponent{

  public studyEnglish:StudyEnglishComponent;

   constructor(english:StudyEnglishComponent){
    this.studyEnglish=english;
    this.sayHai(this.say);
   }

    public say="hi angular !";
   


    public sayHai(params:String) {
    this.studyEnglish.vocabulary();
        return "hi,"+params;
    }

}


  but I get an error like this:  NullInjectorError: R3InjectorError(AppModule)[StudyEnglishComponent -> StudyEnglishComponent -> StudyEnglishComponent]: 
  NullInjectorError: No provider for StudyEnglishComponent!

Understanding Dependency Injection for angular,vue-react-angular-web,angular.js,前端,javascript

 How to solve this problem ?  

1. add @Injectable decorator on StudyEnglishComponent to declare this class is  a provider.

import {Component,Injectable} from "@angular/core";


@Component({"template":"<div>I love studying</div>"})
@Injectable()
export class StudyEnglishComponent{

   
   public vocabulary(){
      console.log("for the record, I have finished my vocabulary today!")
   }

}

2. Use constructor inject the  StudyEnglishComponent 

import { Component } from "@angular/core";

import { StudyEnglishComponent} from "../study/study.english.component";


@Component({
    selector:'hello-word',
    template:'<div class="hello" style="font:200px">hello world</div>',
    styleUrls:['./helloWord.component.css'],
    providers:[StudyEnglishComponent]
})
export class HelloComponent{

  public say="hi angular !";

  public studyEnglish:StudyEnglishComponent;
  
  /**
   * 使用构造器形式注入
   */
  constructor(studyEnglish:StudyEnglishComponent){
    this.studyEnglish=studyEnglish;
    console.log(this.sayHai(this.say));
   }

   


    public sayHai(params:String) {
    this.studyEnglish.vocabulary();
        return "hi,"+params;
    }

}


reboot your serve and see the console:

Understanding Dependency Injection for angular,vue-react-angular-web,angular.js,前端,javascript

 Problem solved !文章来源地址https://www.toymoban.com/news/detail-694888.html

到了这里,关于Understanding Dependency Injection for angular的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • ASP.NET Core 中的 Dependency injection

    依赖注入 (Dependency Injection,简称DI)是为了实现 各个类之间的依赖 的 控制反转 (Inversion of Control,简称IoC )。 ASP.NET Core 中的Controller 和 Service 或者其他类都支持依赖注入。 依赖注入术语中, Service 是一个为其他对象提供服务的类 **。 Service 不是一个Web Service,与Web Serv

    2024年02月11日
    浏览(25)
  • Dependency Injection 8.0新功能——KeyedService

    本文只介绍 .NET Dependency Injection 8.0新功能——KeyedService,假定读者已熟练使用之前版本的功能。 8.0之前,注册一个类往往是 AddSingletonIFoo, Foo() ,8.0添加了一个新功能:“ 可以注册一个带Key的类 ” AddKeyedSingletonIFoo, Foo(\\\"keyA\\\") 。获取服务方法由 GetServiceIFoo() 变成了 GetKeyedServi

    2024年02月08日
    浏览(32)
  • Go 开源库运行时依赖注入框架 Dependency injection

    一个Go编程语言的运行依赖注入库。依赖注入是更广泛的控制反转技术的一种形式。它用于增加程序的模块化并使其具有可扩展性。 依赖注入是更广泛的控制反转技术的一种形式。它用于增加程序的模块化并使其具有可扩展性。 Providing Extraction Invocation Lazy-loading Interfaces Gro

    2024年02月07日
    浏览(42)
  • Spring6-IoC(Inversion of Control)控制反转和DI(Dependency Injection)依赖注入,手动实现IOC

    Java 反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意方法和属性;这种动态获取信息以及动态调用对象方法的功能称为 Java 语言的 反射机制 。简单来说, 反射机制指的是程序在运行时能够获取自身

    2024年02月09日
    浏览(55)
  • 论文笔记--TinyBERT: Distilling BERT for Natural Language Understanding

    标题:TinyBERT: Distilling BERT for Natural Language Understanding 作者:Xiaoqi Jiao, Yichun Yin, Lifeng Shang, Xin Jiang, Xiao Chen, Linlin Li, Fang Wang, Qun Liu 日期:2019 期刊:arxiv preprint   文章提出了一种两阶段的BERT蒸馏模型TinyBERT。TinyBERT在GLUE上击败了所有当前的SOTA蒸馏BERT模型[1],且参数量仅为

    2024年02月15日
    浏览(46)
  • PointMixer: MLP-Mixer for Point Cloud Understanding

    MLP-Mixer 最近崭露头角,成为对抗CNNs和Transformer领域的新挑战者。尽管相比Transformer更为简单,但通道混合MLPs和令牌混合MLPs的概念在图像识别任务中取得了显著的性能。与图像不同,点云本质上是稀疏、无序和不规则的,这限制了直接将MLP-Mixer用于点云理解。为了克服这些限

    2024年01月17日
    浏览(27)
  • 论文阅读《Nougat:Neural Optical Understanding for Academic Documents》

    科学知识主要存储在书籍和科学期刊中,通常以PDF的形式。然而PDF格式会导致语义信息的损失,特别是对于数学表达式。我们提出了Nougat,这是一种视觉transformer模型,它执行OCR任务,用于将科学文档处理成标记语言,并证明了我们的模型在新的科学文档数据集上的有效性。

    2024年02月09日
    浏览(37)
  • 【论文精读】BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding

    自然语言处理(Natural Language Processing,NLP)领域内的 预训练语言模型 ,包括基于RNN的ELMo和ULMFiT,基于Transformer的OpenAI GPT及Google BERT等。预训练语言模型的成功,证明了我们可以从海量的无标注文本中学到潜在的语义信息,而无需为每一项下游NLP任务单独标注大量训练数据。

    2024年02月14日
    浏览(42)
  • 论文笔记--ERNIE 2.0: A Continual Pre-Training Framework for Language Understanding

    标题:ERNIE 2.0: A Continual Pre-Training Framework for Language Understanding 作者:Yu Sun, Shuohuan Wang, Yukun Li, Shikun Feng, Hao Tian, Hua Wu, Haifeng Wang 日期:2020 期刊:AAAI   文章给出了一种新的NLP预训练模型的训练方法,并提出了ERNIE2.0(Enhanced Representation through kNowledge IntErgration)。ERNIE2.0在ERNIE

    2024年02月09日
    浏览(40)
  • 21、LiDAR-LLM: Exploring the Potential of Large Language Models for 3D LiDAR Understanding

    官网  将原始LiDAR数据作为输入,利用LLMs卓越的推理能力,来获得对室外3D场景的全面了解,将3D户外场景认知重构为语言建模问题,如3D captioning, 3D grounding, 3D question answering。  给定LiDAR输入 L ∈ R n × 3 L in R^{n times 3} L ∈ R n × 3 ,n 是点的数量,使用 VoxelNet 获取 LiDAR Fe

    2024年01月21日
    浏览(29)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包