我看到一个服务 (BService) 注入(inject)另一个服务 (AService) 的代码:
(function() {
"use strict"
class AService {
constructor(BService) {
this.BService = BService;
}
static AFactory(BService) {
return new AService(BService);
}
}
AService.AFactory.$inject = ['BService'];
angular.module('test').service('AService', AService.AFactory);
})();
AService.AFactory.$inject
在做什么?为什么我们在这里需要 AFactory?我可以在这里删除 AFactory 吗?我想将上述服务转换为以下 Angular 2 服务。我说得对吗?
import { Injectable } from '@angular/core'; import { BService } from './b.service' @Injectable() export class AService { constructor(private BService: BService) { } } angular.module('test').service('AService', AService);
最佳答案
To allow the minifiers to rename the function parameters and still be able to inject the right services, the function needs to be annotated with the
$inject
property. The$inject
property is an array of service names to inject.
所以,代码也可以写成:
angular.module('test').service('AService', ['BService', function(bService) {
// AService logic goes here,
// injected BService may be used under bService variable
...
}]);
您的代码显示的只是使用新的 JS 类和静态方法 AFactory
实现的相同代码,它通过其类传递给 test
模块:AService .AFactory
2.除了最后一行是多余的,你的代码是正确的。这是一个 official guide关于依赖注入(inject)。请参阅 src/app/heroes/hero.service.ts
中的服务示例:
1 : https://angular.io/guide/dependency-injection#!#why-di
import { Injectable } from '@angular/core';
import { HEROES } from './mock-heroes';
@Injectable()
export class HeroService {
getHeroes() { return HEROES; }
}
然后,需要从组件或模块“提供”服务(上面的 src/app/heroes/heroes.component.ts link ):
import { Component } from '@angular/core';
import { HeroService } from './hero.service';
@Component({
selector: 'my-heroes',
providers: [ HeroService ],
template: `
<h2>Heroes</h2>
<hero-list></hero-list>
`
})
export class HeroesComponent { }
在 Angular 2+ 中,模块是用 @NgModule
注释定义的,服务的注册类似于组件下的 providers
属性。请参阅注册了 UserService
的示例(来自上面 link 的 src/app/app.module.ts):
// imports here
@NgModule({
imports: [
BrowserModule
],
declarations: [
AppComponent,
CarComponent,
HeroesComponent,
/* . . . */
],
providers: [
UserService,
{ provide: APP_CONFIG, useValue: HERO_DI_CONFIG }
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
您的 ng2 代码可以重写为: //a.服务.ts
import { Injectable } from '@angular/core';
import { BService } from './b.service'
@Injectable()
export class AService {
constructor(private bService: BService) {
}
}
并在任何模块中注册:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { AService } from ''./a.service'';
@NgModule({
imports: [
BrowserModule
],
declarations: [
AppComponent,
/* . . . */
],
providers: [ AService ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
关于angularjs - 当我们有一个服务注入(inject)另一个服务时,将 angularjs 服务转换为 angular 2 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45290777/