首页 > 语言 > JavaScript > 正文

Angular 4依赖注入学习教程之Injectable装饰器(六)

2024-05-06 15:16:20
字体:
来源:转载
供稿:网友

学习目录

Angular 4 依赖注入教程之一 依赖注入简介 Angular 4 依赖注入教程之二 组件服务注入 Angular 4 依赖注入教程之三 ClassProvider的使用 Angular 4 依赖注入教程之四 FactoryProvider的使用 Angular 4 依赖注入教程之五 FactoryProvider配置依赖对象 Angular 4 依赖注入教程之六 Injectable 装饰器 Angular 4 依赖注入教程之七 ValueProvider的使用 Angular 4 依赖注入教程之八 InjectToken的使用

本文主要给大家介绍的是关于Angular 4依赖注入之Injectable装饰器的相关内容,分享出来供大家参考学习,下面来看看详细的介绍:

本系列教程的开发环境及开发语言:

Angular 4 + Angular CLI TypeScript

基础知识

装饰器是什么

它是一个表达式 该表达式被执行后,返回一个函数 函数的入参分别为 targe、name 和 descriptor 执行该函数后,可能返回 descriptor 对象,用于配置 target 对象 

装饰器的分类

类装饰器 (Class decorators) 属性装饰器 (Property decorators) 方法装饰器 (Method decorators) 参数装饰器 (Parameter decorators)

TypeScript 类装饰器

类装饰器声明:

declare type ClassDecorator = <TFunction extends Function>(target: TFunction) =>  TFunction | void

类装饰器顾名思义,就是用来装饰类的。它接收一个参数:

target: TFunction - 被装饰的类

看完第一眼后,是不是感觉都不好了。没事,我们马上来个例子:

function Greeter(target: Function): void { target.prototype.greet = function (): void { console.log('Hello!'); }}@Greeterclass Greeting { constructor() { // 内部实现 }}let myGreeting = new Greeting();myGreeting.greet(); // console output: 'Hello!';

上面的例子中,我们定义了 Greeter 类装饰器,同时我们使用了 @Greeter 语法,来使用装饰器。

Injectable 类装饰器使用

import { Injectable } from '@angular/core';@Injectable()class HeroService {}

Injectable 装饰器

在介绍 Injectable 装饰器前,我们先来回顾一下 HeroComponent 组件:

@Component({ selector: 'app-hero', template: ` <ul> <li *ngFor="let hero of heros"> ID: {{hero.id}} - Name: {{hero.name}} </li> </ul> `})export class HeroComponent implements OnInit { heros: Array<{ id: number; name: string }>; constructor(private heroService: HeroService, private loggerService: LoggerService) { } ngOnInit() { this.loggerService.log('Fetching heros...'); this.heros = this.heroService.getHeros(); }}

在 HeroComponent 组件的 ngOnInit 生命周期钩子中,我们在获取英雄信息前输出相应的调试信息。其实为了避免在每个应用的组件中都添加 log 语句,我们可以把 log 语句放在 getHeros() 方法内。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选