angular - 如何从其他组件访问 app.component 的方法?

标签 angular typescript

我是 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/

相关文章:

angular - Angular 和 microsoft msal 的 acquireTokenSilent 失败并显示 AADB2C90077/AADB2C90205

Angular 2 更改事件 - 模型更改

javascript - 如何在 Ionic 2 应用程序中使用 MathJax

typescript - Angular2路由,使用TypeScript,编译报错,获取意外token Console报错

javascript - 处理 promise 错误的最佳方法是什么?

typescript - 使用 vscode 调试 nest.js 应用程序

Angular 7 : Can't bind to 'directive' since it isn't a known property of 'element'

使用(提交)时 Angular 单元测试失败

Angular2 "no exported member bootstrap"错误

javascript - 对象可能是字符串值 'undefined' 上的 Typescript 中的 ''