angular4.x的学习笔记--服务与依赖注入
2018-03-27 10:54
761 查看
服务与依赖注入
服务是什么概念?可以简单地认为它是一个功能模块,重要在于它是单例对象,并且可以注入到其他的地方使用。依赖注入是来自后端的概念,其实就是自动创建一个实例,省去每次需要手动创建的麻烦。
在Angular中定义一个服务很简单,主要在类之前加上
@Injectable装饰器的功能。这是最常见的依赖注入方式useClass,其他具体参见这里。
import { Injectable } from '@angular/core'; @Injectable() export class Service { counter: number = 0; getData(){ return this.counter++; } }然后在模块的
providers中声明:
import { Service } from './service'; ... @NgModule({ imports: [ ... ], declarations: [ ... ], providers: [ Service ], // 注入服务 bootstrap: [...] }) export class AppModule { }使用的时候需要在构造器中建立关联:
import { Component } from '@angular/core'; import { Service } from './service'; ... @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { constructor(public service: Service) { // this.service被成功注入 // 相当于 this.service = new Service(); // 然后可以调用服务 this.service.getData(); } }由于该服务是在模块中注入,所以该模块中的所有组件使用这个服务时,使用的都是同一个实例。
除了在模块中声明,还可以在组件中声明。假设
AppComponent下还有组件
HomeComponent,此时我们在
AppComponent中注入这个服务:
import { Component } from '@angular/core'; import { Service } from './service'; ... @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], providers: [ Service ], // 注入服务 }) export class AppComponent { constructor(public service: Service) { // this.service被成功注入 // 相当于 this.service = new Service(); // 然后可以调用服务 this.service.getData(); } }如果
HomeComponent也使用了这个服务,那它使用的将是同一个实例。这个可以从Service中的数据变化来看出。
Angular还有个分层依赖注入的概念,也就是说,你可以为任一组件创建自己独立的服务。就像上面的例子,如果想要
HomeComponent不和它的父组件同使用一个服务实例的话,只要在该组件中重新注入即可:
... @Component({ selector: 'home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'], providers: [ Service ], // 重新注入服务 }) export class HomeComponent { ... }对于前后端的接口,通常会写成服务。下面说下请求后端数据这块应该怎么写。在模块这节中提过,http有专门的
HttpModule模块处理请求。首先要在模块中导入
HttpModule,然后引入http服务,调用相应的请求方法即可。
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/toPromise'; @Injectable() export class HttpService { constructor(private http: Http) {} getFromServer():any { return this.http.get(`/data`) .toPromise() .then(res => res.json()) .catch(); } }由于请求返回的对象是个可观察对象,可以转成Promise对象处理。这里需要用到RxJS的
toPromise操作符,然后用
then去处理返回成功结果,
catch处理失败情况。这样就搞定了后端数据的请求了。
RxJS又是另外一个比较高深的话题了,有机会深入学习一下再聊。
相关文章推荐
- ng2 学习笔记(三)依赖注入与服务
- (7)学习笔记 ) ASP.NET CORE微服务 Micro-Service ---- 利用Polly+AOP+依赖注入封装的降级框架
- 【Spring学习笔记三】-依赖注入的两种方式
- 微软企业库4.1学习笔记(二十六)Unity依赖注入模块3
- Spring学习笔记(5)----依赖注入的简单实现
- Spring学习笔记(8)-----------依赖注入
- Dagger2 Android依赖注入学习笔记
- Spring学习笔记(6)----编码剖析Spring依赖注入的原理
- Spring4学习笔记----Spring的依赖注入详解
- 依赖注入及企业库Unity组件学习笔记
- 微软企业库4.1学习笔记(五)对象创建和依赖注入方法
- 【ASP.NET MVC 学习笔记】- 05 依赖注入工具Ninject
- spring学习笔记(一)——控制反转&依赖注入
- EJB3.0学习笔记之四 依赖注入(dependency injection)
- 【Spring学习笔记】依赖注入
- spring学习笔记03--依赖注入与控制反转
- AngularJS学习笔记之依赖注入
- AngularJS学习笔记之依赖注入详解
- (学习笔记)spring入门之Bean的依赖注入
- Angular学习笔记(六)之依赖注入入门