[英]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設置bulletchart.service的ID屬性的ngOnInit
但是當我現在嘗試使用this.bulletchart.drawRange();
僅為ID 1而不是 ID 2調用此方法。
我不明白為什么,因為我認為它會執行以下操作:
編輯:
我在我的bulletchart.component文件中添加了providers: [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 { }
檢查此柱塞 。
希望這可以幫助!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.