2016-10-20 21 views
5

Jestem nowy w maszynopisie i Angular 2. Próbowałem szukać odpowiedzi w sieci, ale wygląda na to, że nie działają one dla mnie.Jak uzyskać dostęp do metody z app.component z innego komponentu?

że mam app.component jak pokazano poniżej:

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"); 
    } 
} 

Teraz chcę otworzyć TestingFunction w moim app.component w drugiej klasie, jak pokazano poniżej:

export class BuyTestComponent { 

    constructor(private _testService: TestService) { 
    } 

    public pageTitle: string = "ALL PRACTICE TEST SERIES"; 

    TestHere() { 
     // should call TestingFunction() here..... 
    } 
} 

Jak to zrobić? Proszę o pomoc

Odpowiedz

6

Jeśli potrzebujesz dostępu do funkcji z kilku miejsc, rozważ puttę ng to w usłudze jako @tibbus wymienione.

utility.service.ts

@Injectable() 
export class UtilityService{ 

    TestingFunction(){} 
} 

Następnie upewnij się, że usługa jest wymieniona w tablicy providers swojego głównego modułu:

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 { } 

Możesz wtedy wprowadzić tę usługę w dowolnym komponencie, który potrzebuje dostępu do Funkcja e

buy-test.component.ts

@Component(...) 
export class BuyTestComponent { 

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

    TestHere() { 
     //access service function 
     this.util.TestingFunction(); 
    } 
} 
Powiązane problemy