Angular(二) Understanding Dependency Injection for angular

这篇具有很好参考价值的文章主要介绍了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.

 Angular(二) 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!

Angular(二) 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:

Angular(二) Understanding Dependency Injection for angular,vue-react-angular-web,angular.js,前端,javascript

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

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

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

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

相关文章

  • Infragistics Adds Support for Angular 17

    Ignite UI for Angular 23.1 (17.0.0) takes advantage of the performance related optimizations in the latest Angular release. Infragistics Ignite UI for Angular is a comprehensive library of Angular-native UI controls and Material-based UI components, which includes a high-performance data grid and over 60 charts. Its WYSIWYG app builder helps you streamline y

    2024年02月04日
    浏览(44)
  • Reporting tool for Angular 2023.3.1 Crack

    Stimulsoft Reports.ANGULAR is a cross-platform set of tools for report creating developed to be used in conjunction with the Angular framework. Our solution is compatible with Angular 13 and above, and contains everything you need to create, edit, view and export reports. The server side of the product uses .NET Core and ASP.NET MVC.   Our report writer is

    2024年02月12日
    浏览(39)
  • 深入Angular:(转&翻)Do you still think that NgZone (zone.js) is required for change detection in Angular?

    原文链接:IndepthApp 前言概览:注意区分NgZone和zone.js, 更多细节在Angular跟新策略篇,尚未翻译完成。 本文主要解释了Angular是如何基于zone.js实现NgZone。 同时阐述如何在不使用zone.js的情况下,实现手动更新。文章最后部分将描述自动跟新策略何时会失效。 我看过的大多数文章

    2024年01月16日
    浏览(54)
  • 什么是依赖注入(Dependency Injection)?

    依赖注入(Dependency Injection,简称DI)是一种设计模式,用于实现类之间的解耦和依赖关系的管理。它通过将依赖关系的创建和维护责任转移到外部容器中,使得类不需要自己实例化依赖对象,而是由外部容器动态地注入依赖。 传统的对象创建方式往往由类自身负责创建和管

    2024年02月15日
    浏览(43)
  • 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日
    浏览(38)
  • 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日
    浏览(42)
  • Go 开源库运行时依赖注入框架 Dependency injection

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

    2024年02月07日
    浏览(52)
  • angular前端环境搭建、安装angular

    1.下载node.js安装包(要求node版本大于12.20) Node.js官方网站 : https://nodejs.org/en/ 进入官网后,当前页面下载的是最新版本,如需要下载历史版本,点击红框标注的其他下载,在进入的新的页面底部,选择红框标准的先前版本,然后下载相应的版本,在跳转的页面下载win64的版

    2024年02月03日
    浏览(58)
  • 【Angular开发】Angular中的高级组件

    在这个博客中,我将解释Angular中的几个高级组件和机制,它们增强了灵活性、可重用性和性能。 通过熟悉这些高级组件和机制,您可以提高您的Angular开发技能,并在应用程序中利用灵活性、可重用性和性能优化的能力。让我们开始吧! NgContent NgContent,或Angular中的内容投影

    2024年02月04日
    浏览(54)
  • Angular 11到升级到 Angular 16

    日新月异,与时俱进… 随着Angular版本不断更新,再看所开发的项目版本仍然是Angular 11,于是准备升级 截止发博日最版本是 v17.1.0,考虑到稳定性因素决定升级到v16版本 执行命令行 但是发现直接报错了… 红色字体大概意思就是: 迁移失败:发现不兼容的对等依赖项 安装依

    2024年02月04日
    浏览(35)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包