要实现Angular中不同实例共享相同的defs,可以使用Angular的服务(service)来实现。服务是一种可用于在多个组件之间共享数据和功能的机制。
下面是一个示例代码:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class SVGService {
private defs: string = '';
constructor() { }
setDefs(defs: string) {
this.defs = defs;
}
getDefs() {
return this.defs;
}
}
import { Component, OnInit } from '@angular/core';
import { SVGService } from './svg.service';
@Component({
selector: 'app-svg-component',
template: `
`,
})
export class SVGComponent implements OnInit {
defs: string = '';
constructor(private svgService: SVGService) { }
ngOnInit() {
// 获取defs
this.defs = this.svgService.getDefs();
}
}
import { Component, OnInit } from '@angular/core';
import { SVGService } from './svg.service';
@Component({
selector: 'app-another-component',
template: `
`,
})
export class AnotherComponent implements OnInit {
constructor(private svgService: SVGService) { }
ngOnInit() { }
setDefs() {
const defs = ' ';
this.svgService.setDefs(defs);
}
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { SVGService } from './svg.service';
import { SVGComponent } from './svg.component';
import { AnotherComponent } from './another.component';
@NgModule({
imports: [BrowserModule],
declarations: [SVGComponent, AnotherComponent],
providers: [SVGService],
bootstrap: [SVGComponent, AnotherComponent]
})
export class AppModule { }
这样,不同的SVGComponent实例就可以共享相同的defs了。当点击AnotherComponent中的按钮时,defs将被更新并传递给SVGComponent。