angular2 外包代码在服务中

angular2 outsource code in service

我有一个 angular2 应用程序,它显示休息时的图表数据 api。 我在 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>

app.bulletchart 的模板是这样的:

<div class="panel test{{ID}}">
</div>

在我的 bulletchart.service 文件中,我使用一些方法更改了 app-bulletchart 的 DOM这个:

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

console.log("ident " + identifier);
this.svg = d3.select(identifier).append('svg')
  .attr('class', 'bullet')

还有更新图表的方法

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 属性

但是,当我现在尝试使用 this.bulletchart.drawRange(); 时,此方法仅对 ID 1 调用, 对 ID 2 调用。

我不明白为什么,因为我认为它会做这样的事情:

编辑:

我将 providers: [BulletchartService] 添加到我的 bulletchart.component 文件并将其从 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 { }

检查此 Plunker

希望对您有所帮助!!