前端框架Aurelia - 依赖注入Dependency Injection(一)
Let's say we have a 我们不想把Ajax请求写在CustomerEditScreen里面,我们把Ajax请求放在CustomerService里面,这样任何class都可以利用这个文件请求。Aurelia's dependency injection container 通过在创建时候声明CustomerEditScreen需要
Typically,you would use Decorators,an ES Next feature supported by both Babel and TypeScript. Here's what it looks like to declare that the
import {CustomerService} from 'backend/customer-service'; import {inject} from 'aurelia-framework'; @inject(CustomerService) export class CustomerEditScreen { constructor(private customerService: CustomerService) { this.customer = null; } activate(params) { return this.customerService.getCustomerById(params.customerId) .then(customer => this.customer = customer); } } Notice that we use the 我们用inject修饰符,构造函数匹配inject里面列出的依赖。注意,构造函数里面的依赖必须要一一对应inject修饰符里里面的。这个告诉DI,它任何时候想要创建CustomerEditScreen实例,必须首先获得CustomerService实例,这个要获得的实例可以在CustomerEditScreen实例化的时候被注入到CustomerEditScreen的构造函数中。
多个依赖的注入需要构造函数里面的依赖和inject里面的依赖一一对应。
import {CustomerService} from 'backend/customer-service'; import {CommonDialogs} from 'resources/dialogs/common-dialogs'; import {EventAggregator} from 'aurelia-event-aggregator'; import {inject} from 'aurelia-framework'; @inject(CustomerService,CommonDialogs,EventAggregator) export class CustomerEditScreen { constructor(private customerService: CustomerService,private dialogs: CommonDialogs,private ea: EventAggregator) { this.customer = null; } activate(params) { return this.customerService.getCustomerById(params.customerId) .then(customer => this.customer = customer) .then(customer => this.ea.publish('edit',customer)); } } If you are using TypeScript,you can take advantage of an experimental feature of the language to have the TypeScript transpiler automatically provide Type information to Aurelia's DI. You can do this by configuring the TypeScript compiler with the 如果用的是ts,那么只需要进行上述的配置就可以自动注入依赖。inject换成了autoinject。
Interestingly,you don't need to use our 其实如果用ts,连autoinject都不需要添加,之所以添加,只是为了让代码更清晰。
import {CustomerService} from 'backend/customer-service';
import {CommonDialogs} from 'resources/dialogs/common-dialogs';
import {EventAggregator} from 'aurelia-event-aggregator';
import {autoinject} from 'aurelia-framework';
@autoinject
export class CustomerEditScreen {
constructor(private customerService: CustomerService,247)">If you aren't using Babel's or TypeScript's decorator support (or don't want to),you can easily provide |