【问题标题】:angular2 outsource code in serviceangular2 服务中的外包代码
【发布时间】:2017-11-23 11:03:48
【问题描述】:

我有一个 angular2 应用程序,它显示来自 rest 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。

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

  • 创建 App-Bulletchart (ID=1) -> 创建 bulletchart.service 实例(ID = 1)
  • 创建 App-Bulletchart (ID=2) -> 创建 bulletchart.service 实例(ID = 2)

编辑:

我将providers: [BulletchartService] 添加到我的bulletchart.component 文件中,并将其从app.module 中删除,现在它可以工作了。 但是为什么呢?!

【问题讨论】:

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

标签: javascript angular angular-services angular-components


【解决方案1】:

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

@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

希望对你有帮助!!

【讨论】:

    猜你喜欢
    • 2017-05-19
    • 2016-03-27
    • 2016-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    相关资源
    最近更新 更多