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

时间:2016-10-20 03:34:26

标签: 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.....
    }
}

怎么做?请帮忙

5 个答案:

答案 0 :(得分:18)

如果您需要从多个地方访问某个功能,请考虑将其置于@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 { }

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

购买-test.component.ts

@Component(...)
export class BuyTestComponent {

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

    TestHere() {
        //access service function
        this.util.TestingFunction();
    }
}

答案 1 :(得分:4)

Angular2有两种方式在两个组件之间进行通信:

  1. 如果组件具有父子关系,则通过@Input / @Output
  2. 通过服务
  3. 本文详细介绍了Angular2文档中的两种方式:https://angular.io/docs/ts/latest/cookbook/component-communication.html

答案 2 :(得分:1)

假设您的类AppCompenent保存为app.component.ts 然后在BuyTestComponent类中,您需要先将其导入AppComponent,如下所示

import {AppComponent} from '../app.component';

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

按如下所示在构造函数中实例化

constructor(public myapp: AppComponent){}

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

this.myapp.testingFunction();

最后,您需要在app.module.ts

中将其注册为提供程序。
providers: [
 AppComponent,
]

答案 3 :(得分:0)

我认为最简单的方法是在onInit时填充的应用程序组件中创建一个静态属性

在app.component中


export class AppComponent implements OnInit {
  static myapp;

 ngOnInit() {
    AppComponent.myapp = this;
 }
}

然后在您的组件中

import { AppComponent } from '../../app.component';
export class UsersComponent  implements OnInit {

 ngOnInit() {
    console.log(AppComponent.myapp);
 }
}

答案 4 :(得分:0)

您可以使用事件,例如:

app.component.ts

<div class="row last new-product">
    <div class="col-lg-4">
        <label for="product">Product</label>
        @if($products)
            <select class="form-control kt-select2 products" id="kt_select2_2" name="products[]">
                <option selected disabled>Select a product</option>
                @foreach($products as $product)
                    <option value="{{ $product->id }}" data-price="{{ $product->selling_price }}">{{ $product->name }}</option>
                @endforeach
            </select>
        @endif
    </div>

    <div class="col-lg-4">
        <div class="form-group">
            <label for="product_code">Product Code</label>
            <input type="text" class="form-control" id="product_code" name="product_code[]" placeholder="Enter product code" value="{{ old('product_code') }}">
        </div>
    </div>

    <div class="col-lg-4">
        <div class="form-group">
            <label for="quantity">Product Quantity</label>
            <input type="number" class="form-control" id="quantity" name="quantity[]" placeholder="Enter product quantity" value="{{ old('quantity') }}">
        </div>
    </div>

    <div class="col-lg-4">
        <div class="form-group">
            <label for="price">Product Price</label>
            <input type="text" class="form-control" id="price" name="price[]" placeholder="Enter product price" value="{{ old('price') }}">
        </div>
    </div>

    <div class="col-lg-4">
        <div class="form-group">
            <label for="discount">Product Discount</label>
            <div class="input-group">
                <div class="input-group-prepend"><span class="input-group-text"><i class="fal fa-percentage"></i></span></div>
                <input type="text" id="discount" name="discount[]" class="form-control" placeholder="Enter product discount">
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="form-group">
            <label for="actions">Actions</label>
            <div class="input-group">
                <span id="add-product"><i class="fal fa-plus"></i> Add product</span>
                <span id="delete-product">Delete</span>
            </div>
        </div>
    </div>
</div>

另一个类

import { Events } from 'ionic-angular';
  constructor(public events: Events) {
    events.subscribe('myEvent', () => {
      this.myMethod();
    });
  }

  myMethod() {
    console.log("my method was activated");
  }