2016-10-20 4 views
5

Я новичок в Typcript и Angular 2. Я попытался найти ответ в Интернете, но кажется, что они не работают для меня.Как получить доступ к методу из app.component из другого компонента?

Скажем, у меня есть app.component, как показано ниже:

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

Теперь я хочу, чтобы получить доступ к TestingFunction в моем app.component в другом классе, как показано ниже:

export class BuyTestComponent { 

    constructor(private _testService: TestService) { 
    } 

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

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

Как это сделать? Пожалуйста, помогите

ответ

6

Если вам нужен доступ к функции из нескольких мест, рассмотрите putti это в службе, о которой упоминал @tibbus.

utility.service.ts

@Injectable() 
export class UtilityService{ 

    TestingFunction(){} 
} 

Далее, убедитесь, что служба указана в providers массиве основного модуля:

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

Затем вы можете ввести эту услугу в любой компонент, который нуждается в доступе к th е функция

бай-test.component.ts

@Component(...) 
export class BuyTestComponent { 

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

    TestHere() { 
     //access service function 
     this.util.TestingFunction(); 
    } 
} 
Смежные вопросы