How to access a method from app.component from other component?

angular, typescript

Solution

If you need access to a function from several places, consider putting it in a service as @tibbus mentioned.

utility.service.ts

@Injectable()
export class UtilityService{

    TestingFunction(){}
}

Next, make sure the service is listed in the `providers` array of your main module:

app.module.ts

// https://angular.io/docs/ts/latest/guide/ngmodule.html#!#ngmodule-properties
@NgModule({ 
  imports:      [ BrowserModule],
  declarations: [ AppComponent, BuyTestComponent ],
  providers:    [ UtilityService ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

You can then inject that service in any component that needs access to the function

buy-test.component.ts

@Component(...)
export class BuyTestComponent {

    //inject service into the component
    constructor(private util:UtilityService){}

    TestHere() {
        //access service function
        this.util.TestingFunction();
    }
}

Problem

I am new to Typescript and Angular 2. I tried to look for an answer in the web but it seems they don't work for me. Say I have an app.component as shown below: ``` export class AppComponent implements OnInit { constructor(public _testService: TestService) { } listForCart = this._testService.getListForCart(); cartCount = this.listForCart.length; cartPayableAmount = 0; ngOnInit() { this.computeTotal(); } TestingFunction(){ console.log("Got here"); } } ``` Now I want to access the TestingFunction in my app.component in other class as shown below: ``` export class BuyTestComponent { constructor(private _testService: TestService) { } public pageTitle: string = "ALL PRACTICE TEST SERIES"; TestHere() { // should call TestingFunction() here..... } } ``` How to do that? Please help

Original source