我是 Typescript 和 Angular 2 的新手。我试图在网上寻找答案,但似乎它们对我不起作用。
假设我有一个如下所示的 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");
}
}
现在我想访问其他类中我的 app.component 中的 TestingFunction,如下所示:
export class BuyTestComponent {
constructor(private _testService: TestService) {
}
public pageTitle: string = "ALL PRACTICE TEST SERIES";
TestHere() {
// should call TestingFunction() here.....
}
}
该怎么做?请帮忙
最佳答案
如果您需要从多个地方访问某个功能,请考虑将其放入@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 { }
然后您可以将该服务注入(inject)到任何需要访问该功能的组件中
buy-test.component.ts
@Component(...)
export class BuyTestComponent {
//inject service into the component
constructor(private util:UtilityService){}
TestHere() {
//access service function
this.util.TestingFunction();
}
}
关于angular - 如何从其他组件访问 app.component 的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40145002/