Angular 4依赖注入学习教程之组件服务注入(二)

前端之家收集整理的这篇文章主要介绍了Angular 4依赖注入学习教程之组件服务注入(二)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

学习目录

前言

之前的已经介绍了Angular 4 的基础知识,下面将介绍Angular 4依赖注入之组件服务注入的相关内容分享出来供大家参考学习,下面来来看看详细的介绍:

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

基础知识

如何创建 Angular 组件

中我们通过以下方式创建一个简单的组件:

{{title}} ` }) export class AppComponent { title: string = 'App Works'; }

如何创建 Angular 服务

中我们通过以下方式创建一个简单的服务:

组件中注入服务

介绍完基础知识,接下来我们来创建一个新的组件 - HeroComponent,它用来显示英雄的信息,具体实现如下:

@Component({
selector: 'app-hero',template: `

` }) export class HeroComponent implements OnInit { heros: Array<{ id: number; name: string }>;

ngOnInit() {
this.heros = [
{ id: 11,name: 'Mr. Nice' },{ id: 12,name: 'Narco' },{ id: 13,name: 'Bombasto' },{ id: 14,name: 'Celeritas' },{ id: 15,name: 'Magneta' }
];
}
}

在 HeroComponent 组件中,我们在 ngOnInit 钩子中进行数据初始化,然后利用 ngFor 指令来显示英雄列表的信息。创建完 HeroComponent 组件,我们要来验证一下该组件的功能

首先在 AppModule 中导入 HeroComponent 组件,具体如下:

@NgModule({
declarations: [
AppComponent,HeroComponent
],...
})
export class AppModule { }

然后更新一下 AppComponent 组件,具体如下:

@Component({
selector: 'app-root',template: @H_<a href="https://www.jb51.cc/tag/301/" target="_blank" class="keywords">301</a>_64@</app-hero>
})
export class AppComponent {}

如果不出意外的话,访问 http://localhost:4200/ 页面,您将看到如下信息:

难道一切就这么结束了,No! No!别忘记了我们这节课的主题是介绍如何在组件中注入服务。在目前的 HeroComponent 组件,我们的英雄列表信息是固定的,在实际的开发场景中,一般需要从远程服务器获取相应的信息。但我们暂不考虑这个问题,假设另外一个组件也需要利用同样的英雄列表信息,那我们要怎么办,难道直接上 "终极绝招" - Copy && Paste 。当然这是 "终极绝招",岂能随便使用 (不怕被群殴的话,请自便哈)。

针对上面提到的问题,理想的方式是创建一个 HeroService 服务,从而实现数据共享

说干就干,我们马上来创建 HeroService 服务,具体如下:

= [ { id: 11,name: 'Magneta' } ];

getHeros() {
return this.heros;
}
}

在 HeroService 服务中,我们定义了一个 heros 属性和一个 getHeros() 方法

  • heros - 用于保存英雄的列表信息
  • getHeros() - 用于获取英雄的列表信息

创建完 HeroService 服务后,接下来我们来介绍如何在组件中使用 HeroService 服务。

组件中使用 HeroService

组件中使用 HeroService 服务,主要分为三个步骤:

1、导入 HeroService 服务

2、声明 HeroService 服务

注入 HeroService 服务

完整代码如下:

@Component({
selector: 'app-hero',template: `

`,providers: [HeroService] }) export class HeroComponent implements OnInit {

constructor(private heroService: HeroService) { }

heros: Array<{ id: number; name: string }>;

ngOnInit() {
this.heros = this.heroService.getHeros();
}
}

看到 providers: [HeroService] 这一行,相信有一些读者会有一些困惑,因为他们可能是按照下面的方式去配置 HeroService 服务。

当然两种方式不会影响,我们最终要实现的功能,但这两种方式肯定是有区别的,希望有兴趣的读者,去思考一下哈。在多数场景下,推荐在 NgModule 的 Metadata 信息中配置相应的服务。

我有话说

为什么配置完 HeroService,在 HeroComponent 组件类的构造函数中还得进行类型声明?

export class HeroComponent implements OnInit {
constructor(private heroService: HeroService) { }
}

其实在 @NgModule({...}) @Component({...}) Metadata 中我们只是配置 Provider 的相关信息,即告诉 Angular DI (依赖注入) 系统,如何创建根据配置的 provider 信息,创建相应的依赖对象。而在 HeroComponent 组件类中,我们通过构造注入的方式去告诉 Angular DI 系统,我们需要的依赖对象类型。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对编程之家的支持

原文链接:https://www.f2er.com/js/38854.html

猜你在找的JavaScript相关文章