Javascript angular2服务外包代码

Javascript angular2服务外包代码,javascript,angular,angular-services,angular-components,Javascript,Angular,Angular Services,Angular Components,我有一个angular2应用程序,可以显示RESTAPI中的图表数据。 我在bulletchart.component文件中创建了绘图代码。 现在我想把代码外包到一个服务中。 但似乎只有一个数据服务的活动实例 这是我要加载图表的页面内容 <div class="col"> <app-bulletchart [ID]="1" [apiAddress]="'http://url1'"></app-bulletchart> </div> <d

我有一个angular2应用程序,可以显示RESTAPI中的图表数据。 我在bulletchart.component文件中创建了绘图代码。 现在我想把代码外包到一个服务中。 但似乎只有一个数据服务的活动实例

这是我要加载图表的页面内容

<div class="col">
   <app-bulletchart [ID]="1" [apiAddress]="'http://url1'"></app-bulletchart>
</div>
<div class="col">
   <app-bulletchart [ID]="2" [apiAddress]="'http://url2'"></app-bulletchart>
</div>
还有一些方法可以更新图表

drawRange() {
console.log("range " + this.ID);

// Update the range rects.
const range = this.g.selectAll('rect.range')
  .data(this.ranges);

range.enter().append('rect')
我在bulletchart.component中的ngOnInit中设置bulletchart.service的ID属性

@Component({
  ...
  providers:[BulletchartService]
  ...
但是当我现在尝试使用
this.bulletchart.drawRange()时
此方法仅针对ID 1调用,而不针对ID 2调用

我不明白为什么,因为我以为它会这样做:

initSvg() {
const identifier = '.test' + this.ID;

console.log("ident " + identifier);
this.svg = d3.select(identifier).append('svg')
  .attr('class', 'bullet')
  • 创建应用程序Bulletchart(ID=1)->创建Bulletchart.service的实例(ID=1)
  • 创建应用程序Bulletchart(ID=2)->创建Bulletchart.service的实例(ID=2)
编辑:

我在bulletchart.component文件中添加了
提供者:[BulletchartService]
,并将其从app.module中删除,现在它可以工作了。
但为什么

您可以在组件中包括服务提供者,以确保为组件的每个实例创建服务

@Component({
  ...
  providers:[BulletchartService]
  ...
})

示例

@Injectable()
export class AppService{
  Id: string;

  someMethod(){
    console.log(this.Id);
  }
}

@Component({
  selector: 'my-child',
  template: `<h1>Child ID {{Id}}</h1>
  <button (click)="invokeService()" >Invoke service</button>
  `,
  providers:[AppService]
})
export class ChildComponent { 
  @Input() Id: string; 

  constructor(private svc: AppService){}

  ngOnInit(){
    this.svc.Id = this.Id;
  }

  invokeService(){
    this.svc.someMethod();
  }
}

@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>
  <my-child [Id]="1" ></my-child>
  <my-child [Id]="2" ></my-child>
  `
})
export class AppComponent { 
  name = 'Angular'; 
}

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent, ChildComponent ],
  bootstrap:    [ AppComponent ]
})

export class AppModule { }
@Injectable()
导出类应用程序服务{
Id:字符串;
someMethod(){
console.log(this.Id);
}
}
@组成部分({
选择器:“我的孩子”,
模板:`Child ID{{ID}}
调用服务
`,
提供商:[AppService]
})
导出类ChildComponent{
@Input()Id:string;
构造函数(私有svc:AppService){}
恩戈尼尼特(){
this.svc.Id=this.Id;
}
invokeService(){
this.svc.someMethod();
}
}
@组成部分({
选择器:“我的应用程序”,
模板:`Hello{{name}}
`
})
导出类AppComponent{
名称='角度';
}
@NGD模块({
导入:[BrowserModule],
声明:[AppComponent,ChildComponent],
引导:[AppComponent]
})
导出类AppModule{}
看看这个


希望这有帮助

我不会使用服务来修改组件。服务被注入,因此您的组件可以使用它们发送和接收数据,并与其他组件通信。组件本身应该负责管理它们自己的状态。@RobZuber但是我应该用什么来外包我的代码呢?