在同一页面Angular中的两个组件之间共享方法 [英] Share methods between two components in same page Angular

查看:320
本文介绍了在同一页面Angular中的两个组件之间共享方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two components in the same page. I have few methods and properties same for both components. How to use that by using a service. Below is a sample code...

@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
}

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

How to use a service to share between these two components which are on the same page.

推荐答案

//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();
  }
 }

这篇关于在同一页面Angular中的两个组件之间共享方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆