非 angular class 如何使用 angular 服务及其部门

How can a non angular class use an angular service and its deps

我正在尝试 link 3 个文件 Angular 组件,纯 JS Class 和 Angular 服务:

我的 angular 组件 (AppComponent) 应该初始化我的普通 js class (CommonCode)...但是,我的普通 js class 需要调用 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 Class

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 class 转换为 Angular 服务并在组件级别提供它。

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  providers: [ CommonCode ],
})
export class AppComponent  {

  ngOnInit() {

  }
}