简体   繁体   中英

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

I am trying to link 3 files Angular Component, Plain JS Class and Angular Service:

My angular component (AppComponent) should initialise my plain js class (CommonCode)... However, my plain js class needs to call and angular service.

Component:

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

  ngOnInit() {

  }
}

Service:

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() {

    }
}

As per comments, you could convert CommonCode TS class to an Angular Service and provide it on Component Level.

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

  ngOnInit() {

  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM