我正在尝试链接 3 个文件 Angular 组件、Plain JS 类和 Angular 服务:我的角度组件(AppComponent)应该初始化我的普通 js 类(CommonCode)...但是,我的普通 js 类需要调用和角度服务。成分:@Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ]})export class AppComponent { ngOnInit() { }}服务:import { AnotherAngularService } from '/core/service2';import { AnotherAnotherAngularService } from '/core/service3';@Injectable({ providedIn: 'root',})export class Foo2Service { this.serviceOneCache = null; // Service code constructor(public anotherAngularService:AnotherAngularService, public anotherAnotherAngularService:AnotherAnotherAngularService) { this.anotherAngularService.getCache().subscribe(response) { this.serviceOneCache = response; } .error(); } init() { // Code that returns something return 'test'; } getFooCache() { return this.http.get...... etc etc }}JS类import { FooService } from '/core/fooservice';export class CommonCode { this.fooCache = null; // Service code constructor(public fooService: FooService) { this.fooService.getFooCache().subscribe(response) { this.fooCache = response; } .error(); } func1() { }}
1 回答
隔江千里
TA贡献1906条经验 获得超10个赞
您可以将CommonCodeTS 类转换为 Angular 服务并在组件级别提供它。
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ],
providers: [ CommonCode ],
})
export class AppComponent {
ngOnInit() {
}
}
添加回答
举报
0/150
提交
取消