angular2 服务实例化 2 次
angular2 service instancied 2 times
我有一个使用 2 个服务的组件。
export class UseComponent {
constructor(private _service1: Service1,
private _service2: Service2){}
第二个服务需要第一个服务中存在的方法。因此我也在 second
中注入了 fisrty 服务
export class Service2{
constructor(private _service1: Service1) {};
getLabel(): string{
return this._service1.getLanguageLabel();
}
服务提供者在模块中
@NgModule({
imports: [.....],
declarations: [.....],
providers: [Service1, Service2]
})
export class UseModule { }
当UseComponent使用方法getLabel时,service1会再次实例化(组件初始化时的第一次实例化)
为什么要第二次实例化?如何避免?
一般工作:https://plnkr.co/edit/pWgQ5iVNVVGmHBZsv2SD?p=preview
请注意这些服务不在任何其他 module
的提供商列表中。
@Injectable()
export class Service1 {
constructor() {
addLog('created service 1');
}
public anyFunc() {
return "huhu";
}
}
@Injectable()
export class Service2 {
constructor(private _srv1: Service1) {
addLog('created service 2');
}
public anyFunc() {
return this._srv1.anyFunc();
}
}
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
</div>
<p *ngFor="let log of logs | async">{{log}}</p>
`,
})
export class App {
name:string;
private logs = logs;
constructor(private _srv2: Service2) {
this.name = 'Angular2'
addLog(this._srv2.anyFunc());
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
providers: [Service1, Service2],
bootstrap: [ App ]
})
export class AppModule { }
我有一个使用 2 个服务的组件。
export class UseComponent {
constructor(private _service1: Service1,
private _service2: Service2){}
第二个服务需要第一个服务中存在的方法。因此我也在 second
中注入了 fisrty 服务export class Service2{
constructor(private _service1: Service1) {};
getLabel(): string{
return this._service1.getLanguageLabel();
}
服务提供者在模块中
@NgModule({
imports: [.....],
declarations: [.....],
providers: [Service1, Service2]
})
export class UseModule { }
当UseComponent使用方法getLabel时,service1会再次实例化(组件初始化时的第一次实例化)
为什么要第二次实例化?如何避免?
一般工作:https://plnkr.co/edit/pWgQ5iVNVVGmHBZsv2SD?p=preview
请注意这些服务不在任何其他 module
的提供商列表中。
@Injectable()
export class Service1 {
constructor() {
addLog('created service 1');
}
public anyFunc() {
return "huhu";
}
}
@Injectable()
export class Service2 {
constructor(private _srv1: Service1) {
addLog('created service 2');
}
public anyFunc() {
return this._srv1.anyFunc();
}
}
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
</div>
<p *ngFor="let log of logs | async">{{log}}</p>
`,
})
export class App {
name:string;
private logs = logs;
constructor(private _srv2: Service2) {
this.name = 'Angular2'
addLog(this._srv2.anyFunc());
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
providers: [Service1, Service2],
bootstrap: [ App ]
})
export class AppModule { }