[英]How can a non angular class use an angular service and its deps
我正在尝试链接 3 个文件 Angular Component、Plain JS Class 和 Angular Service:
我的 angular 组件(AppComponent)应该初始化我的普通 js 类(CommonCode)……但是,我的普通 js 类需要调用和 angular 服务。
成分:
@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() {
}
}
根据评论,您可以将CommonCode
TS 类转换为 Angular 服务并在组件级别提供它。
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ],
providers: [ CommonCode ],
})
export class AppComponent {
ngOnInit() {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.