【问题标题】:How to invoke method from one component to another component in Angular 2?如何在Angular 2中从一个组件调用方法到另一个组件?
【发布时间】:2017-12-08 01:47:26
【问题描述】:

我有两个不同的组件 - 一个组件具有列表用户的单击事件方法,我想继承(调用)详细信息页面上的单击事件方法(另一个组件))

怎么做,请帮帮我...

答案更新

感谢您的回答。

我已经通过在构造函数中使用扩展类和使用 super() 得到了解决方案。

头等舱

export class TeamsView {
   constructor(private test:TestService){
   }
   ...
}

二等

export class TeamsForm extends TeamsView {
   constructor(private test:TestService, private router: Router){
     super(test)
   }
   ...
}

【问题讨论】:

  • copy that click event method on detail page是什么意思?
  • 表示我想将方法​​从一个组件继承到另一个组件...@AJT_82

标签: angular extends super angular2-components


【解决方案1】:

你可以试试这个:

<first-component (click)="mySecondComponent.myFunction()"></first-component>
<second-component #mySecondComponent></second-component>

myFunction 必须是公开的。

【讨论】:

    【解决方案2】:

    在服务中添加常用方法

    import {Injectable} from '@angular/core';
    @Injectable()
    export class MyService {
      constructor() { }
      doSomething(val) { 
        return !val;
      }
    }
    

    通过注入该服务在组件中使用它,一个组件代码如下。在其他组件中也可以这样写。

    import {Component, OnInit} from '@angular/core';
    import {MyService} from './shared/my-service'; // see angular.io/styleguide
    
    @Component({
      selector: '<my-component></my-component>',
      templateUrl: 'app/name.component.html',
      // This is unnecessary when installing MyService within Root NgModule
      providers: [MyService]
    })
    
    export class MyComponent implements OnInit {
    
      value1: boolean = true;
    
      constructor(private ms: MyService) {}
    
      ngOnInit() {  }
    
      click() { 
        this.ms.doSomething(value1);
      }
    }
    

    HTML

    <input type="button" (click)="click()">
    

    【讨论】:

    • 但在我的 Click 事件方法中,有很多对象和变量来自第一个组件。我如何在服务中调用该方法,然后在另一个组件中调用该方法? @维拉
    • 将这些发送到服务方法 doSomething(object1, var1) 并从服务返回响应。
    • 但我不知道该怎么做。因为我是 Angular 2 @Veera 的新手
    • 更新了答案。请检查。
    【解决方案3】:

    1.从一个组件调用方法到另一个组件(如果它们不是父子组件),只能使用服务。

        //FirstComponent
    
        import {Component} from '@angular/core';
        import {CommonService} from './common.service';
    
        @Component({
          selector: '<first-component></first-component>',
          template: 'some html here',
          providers: [CommonService]
        })
    
        export class FirstComponent {
          constructor(private _service: CommonService) {
           this._service.callMethodOfSecondComponent(); 
          }
    
        }
    
    
        //CommonService
    
        import {Subject} from 'rxjs/Subject'; 
    
        @Injectable()
        export class CommonService {
          invokeEvent: Subject<any> = new Subject(); 
    
          callMethodOfSecondComponent() { 
            this.invokeEvent.next(someValue)      
          }
        }
    
    
         //SecondComponent
    
        import {Component, OnInit} from '@angular/core';
        import {CommonService} from './common.service';
    
        @Component({
          selector: '<second-component></second-component>',
          template: 'some html here',
          providers: [CommonService]
        })
    
        export class SecondComponent {
          constructor(private _service: CommonService) {
           this._service.invokeEvent.subscribe(value => {
            if(value === 'someVal'){
             this.callMyMethod(); 
           }
          }); 
          }
    
          callMyMethod(){
          //code block to run
          }
        }
    

    2.从子组件调用父组件的方法

        //Child Component
    
        import {Component} from '@angular/core';
        @Component({
          selector: '<child-component></child-component>',
          template: 'some html here',
        })
    
        export class ChildComponent {
          @Output()
          emitFunctionOfParent: EventEmitter<any> = new EventEmitter<any>();
          constructor() {
          }
    
          someMethodOfChildComponent(){
           this.emitFunctionOfParent.emit(someValue); 
          }
    
        }
    
        //ParentComponent
    
        import {Component} from '@angular/core';
        @Component({
          selector: '<parent-component></parent-component>',
          template: `some html
                    <child-component 
                    (emitFunctionOfParent)="myMethod($event)">
                     </child-component>   
                     some html
                    `,
        })
    
        export class ParentComponent {
          constructor() {
          }
    
          myMethod(someValue){
          // i am called
          }
    
        }
    

    3. 从父组件调用子组件的方法

    //Child Component
    
        import {Component} from '@angular/core';
        @Component({
          selector: '<child-component></child-component>',
          template: 'some html here',
        })
    
        export class ChildComponent {
    
          constructor() {
          }
    
          someMethodOfChildComponentToBeCalled(){
           // i am called
          }
    
        }
    
    
    //Parent Component
    
        import {Component, OnInit} from '@angular/core';
        import {ChildComponent} from './child.component';
        @Component({
          selector: '<parent-component></parent-component>',
           template: `some html
                    <child-component>
                     </child-component>   
                     some html
                    `
        })
    
        export class ParentComponent implements OnInit {
          @ViewChild(ChildComponent) private _child: 
          ChildComponent;
    
          ngOnInit() { 
          this._child.someMethodOfChildComponentToBeCalled();
          }
    
    
    
        }
    

    除了这些之外,可能还有其他的交流方式。 :)

    【讨论】:

    • 感谢上面的#1,这正是我所需要的。然而,直到我从 Stack Overflow “订阅 angular2 不工作”中得知我的问题是“提供者:[CommonService]”在多个位置提供 CommonService,CommonService 的单独实例被实例化时,它才对我有用——所以它毕竟不是“常见的”。我消除了显示的两个“提供者:[CommonService]”,而是在我的应用程序的一个常见 app.module.ts 中提供了 CommonService。 (另外,最好捕获返回的 $subscription 并在 ngOnDestroy() 中执行 .unsubscribe()。)
    【解决方案4】:

    要获得更清洁的解决方案,请遵循此过程。

    注意:在一个组件中调用以下方法,该方法从服务调用事件发射器并将其发射到另一个组件。

        service.ts:   
    
        import {Subject} from 'rxjs/Subject';
    
        private emitter: Subject<any> = new Subject<any>();
    
          set() {
           this.emitter.next({command: 'set', params:{a:1, b:2});
          };   
          getChangeEmitter() {
            return this.emitter;
          }
    
        component.ts
    
        import {Subscription} from 'rxjs/Subscription';
    
          private listener: Subscription;
    
         ngOnInit(): void {
            // Listen for changes in the service
      this.listener = this._service.getChangeEmitter()
          .subscribe(paramsFromService => {
            switch (paramsFromService.command) {
              case 'set':
               this.setMethod(paramsFromService);
                break;
    
              default:
                this.defaultMethod(paramsFromService);
                break;
            }
          });
          }
    

    【讨论】:

      【解决方案5】:

      我已经通过在构造函数中使用扩展类和使用 super() 得到了解决方案。

      头等舱

      export class TeamsView {
          constructor(private test:TestService){
          }
          ...
       }
      

      二等

      export class TeamsForm extends TeamsView {
          constructor(private test:TestService, private router: Router){
            super(test)
          }
          ...
      }
      

      我不知道它在构造函数中调用类来解决这个问题的真正方法,但我从 Angular 站点之一找到了这个,它也对我有用。

      【讨论】:

      • 我还尝试从第二个组件初始化一个新实例,并将其构造函数所需的一切传递给它并且它工作
      【解决方案6】:

      1.) 首先,您需要将第一个组件导入目标组件。

      import { FirstComponent } from '../first.component';
      

      2.) 然后你需要像这样创建第一个组件的对象:

      FirstComponentObject = new FirstComponent();
      

      3.) 然后从目标(当前)组件调用第一个组件的函数

      FirstComponentObject.FirstComponentFunction();
      

      如果您需要任何帮助,请发表评论。感谢阅读。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-14
        • 2017-05-19
        • 2018-07-07
        • 2017-09-07
        • 2017-08-19
        相关资源
        最近更新 更多