在同一页面Angular中的两个组件之间共享方法

时间:2018-05-28 05:32:37

标签: javascript angular typescript

我在同一页面中有两个组件。我对这两个组件的方法和属性都很少。如何使用服务使用它。以下是示例代码......

@Component({
selector: 'app',
template: '<h1>AppComponent1</h1>'
})
export class AppComponent1 { }

@Component({
selector: 'appTwo',
template: '<h1>AppComponent2</h1>'
})
export class AppComponent2 { }

我有两种常见的方法:

onSearch(){
 console.log('search');
}

onBtnClick(){
//do something
}

如何使用服务在同一页面上的这两个组件之间共享。

2 个答案:

答案 0 :(得分:0)

您可以使用双向服务。即使您的组件位于不同的模块中也很有用。

服务

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';

@Injectable()
export class AppShareService {
  private readonly subjectSource$ = new Subject<object>();

  public get newData(): Observable<object> {
    return this.subjectSource$.asObservable();
  }

  public publish(data: any) {
    this.subjectSource$.next(data);
  }
}

你可以像这样发布类似事件的消息:

export class AppComponent {
  constructor(public appShareService: AppShareService ) {
    appShareService.publish({data: 'some data'});
  }
}

您可以订阅这些活动:

export class HomeComponent implements OnDestroy {
  mySubscription: Subscription;

  constructor(public appShareService: AppShareService ) {
    this.mySubscription = appShareService.newData.subscribe((data) => {
      console.log(data); // {data: 'some data'}
    });
  }

ngOnDestroy(): void {
  if (this.mySubscription) {
    this.mySubscription.unsubscribe();
  }
 }
}

良好的做法是始终取消订阅Observable。和ngOnDestroy是个好地方。

答案 1 :(得分:0)

//first make @Injectable service and all your comman functionality like below

import {Injectable} from "@angular/core";


@Injectable()
export class Appshare {
  share:'test'
    constructor( ) { 
     console.log('search');
    }
    onSearch(){
    console.log('search');
    }

    onBtnClick(){
    console.log('btnclick');
    }

}

//than declare it in your component section use direct in your both component

import { Component } from '@angular/core';
import{Appshare} from "./appshare.service";

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  constructor(public appshare:Appshare){
      this.appshare.onSearch();
      this.appshare.onBtnClick();
  }

}


@Component({
selector: 'appTwo',
template: '<h1>AppComponent2</h1>'
})
export class AppComponent2 {
  constructor(public appshare:Appshare){
      this.appshare.onSearch();
      this.appshare.onBtnClick();
  }
 }