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

wal*_*wal 17 typescript angular

我是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");
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我想访问其他类中app.component中的TestingFunction,如下所示:

export class BuyTestComponent {

    constructor(private _testService: TestService) {
    }

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

    TestHere() {
        // should call TestingFunction() here.....
    }
}
Run Code Online (Sandbox Code Playgroud)

怎么做?请帮忙

Bee*_*ice 18

如果您需要从多个地方访问某个功能,请考虑将其置于@tibbus提到的服务中.

utility.service.ts

@Injectable()
export class UtilityService{

    TestingFunction(){}
}
Run Code Online (Sandbox Code Playgroud)

接下来,确保服务列在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 { }
Run Code Online (Sandbox Code Playgroud)

然后,您可以在需要访问该功能的任何组件中注入该服务

买入test.component.ts

@Component(...)
export class BuyTestComponent {

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

    TestHere() {
        //access service function
        this.util.TestingFunction();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 它将调用服务内部的功能而不是应用程序组件中的功能 (2认同)

Yin*_*nka 10

假设你的类 AppCompenent 被保存为 app.component.ts 然后在你的 BuyTestComponent 类中,你需要先像下面这样导入它 AppComponent

import {AppComponent} from '../app.component';
Run Code Online (Sandbox Code Playgroud)

假设两个文件都保存在同一个文件夹中。

在您的构造函数中实例化它,如下所示

constructor(public myapp: AppComponent){}
Run Code Online (Sandbox Code Playgroud)

然后在您的 BuyTestComponent 中调用它,如下所示

this.myapp.testingFunction();
Run Code Online (Sandbox Code Playgroud)

最后,您需要在 app.module.ts 中将其注册为提供者

providers: [
 AppComponent,
]
Run Code Online (Sandbox Code Playgroud)