angular 组件通信的几种实现方式

单页面应用组件通信有以下几种,这篇文章主要讲 Angular 通信

  • 父组件 => 子组件
  • 子组件 => 父组件
  • 组件A = > 组件B
父组件 => 子组件 子组件 => 父组件 sibling => sibling
@input @output
setters (本质上还是@input) 注入父组件
ngOnChanges() (不推荐使用)
局部变量
@ViewChild()
service service service
Rxjs的Observalbe Rxjs的Observalbe Rxjs的Observalbe
localStorage,sessionStorage localStorage,sessionStorage localStorage,sessionStorage

上面图表总结了能用到通信方案,期中最后3种,是通用的,angular的组件之间都可以使用这3种,其中Rxjs是最最牛逼的用法,甩redux,promise,这些同样基于函数式的状态管理几条街,下面一一说来

父组件 => 子组件

@input,最常用的一种方式

@Component({
 selector: 'app-parent',
template: '<div>childText:<app-child [textContent] = "varString"></app-child></div>',
 styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
 varString: string;
 constructor() { }
 ngOnInit() {
  this.varString = '从父组件传过来的' ;
 }
}
import { Component, OnInit, Input } from '@angular/core';
@Component({
 selector: 'app-child',
 template: '<h1>{{textContent}}</h1>',
 styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
 @Input() public textContent: string ;
 constructor() { }
 ngOnInit() {
 }
}

setter

setter 是拦截@input 属性,因为我们在组件通信的时候,常常需要对输入的属性处理下,就需要setter了,setter和getter常配套使用,稍微修改下上面的child.component.ts

child.component.ts

import { Component, OnInit, Input } from '@angular/core';
@Component({
 selector: 'app-child',
 template: '<h1>{{textContent}}</h1>',
 styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
_textContent:string;
 @Input()
 set textContent(text: string){
  this._textContent = !text: "啥都没有给我" ? text ;
 } ;
 get textContent(){
 return this._textContent;
 }
 constructor() { }
 ngOnInit() {
 }
}

onChange

这个是通过angular生命周期钩子来检测,不推荐使用,要使用的话可以参angular文档

@ViewChild()

@ViewChild() 一般用在调用子组件非私有的方法

      import {Component, OnInit, ViewChild} from '@angular/core';
    import {ViewChildChildComponent} from "../view-child-child/view-child-child.component";
  @Component({
   selector: 'app-parent',
   templateUrl: './parent.component.html',
   styleUrls: ['./parent.component.css']
  })
  export class ParentComponent implements OnInit {
   varString: string;
   @ViewChild(ViewChildChildComponent)
   viewChildChildComponent: ViewChildChildComponent;
   constructor() { }
   ngOnInit() {
    this.varString = '从父组件传过来的' ;
   }
   clickEvent(clickEvent: any) {
    console.log(clickEvent);
    this.viewChildChildComponent.myName(clickEvent.value);
   }
  }
   import { Component, OnInit } from '@angular/core';
  @Component({
   selector: 'app-view-child-child',
   templateUrl: './view-child-child.component.html',
   styleUrls: ['./view-child-child.component.css']
  })
  export class ViewChildChildComponent implements OnInit {
   constructor() { }
   name: string;
   myName(name: string) {
     console.log(name);
     this.name = name ;
   }
   ngOnInit() {
   }
  }

局部变量

局部变量和viewChild类似,只能用在html模板里,修改parent.component.html,通过#viewChild这个变量来表示子组件,就能调用子组件的方法了.

<div class="panel-body">
  <input class="form-control" type="text" #viewChildInputName >
  <button class=" btn btn-primary" (click)="viewChild.myName(viewChildInputName.value)">局部变量传值</button>
  <app-view-child-child #viewChild></app-view-child-child>
      </div>

child 组件如下

@Component({
 selector: 'app-view-child-child',
 templateUrl: './view-child-child.component.html',
 styleUrls: ['./view-child-child.component.css']
})
export class ViewChildChildComponent implements OnInit {

 constructor() { }
 name: string;
 myName(name: string) {
   console.log(name);
   this.name = name ;
 }
 ngOnInit() {
 }

}

子组件 => 父组件

@output()

output这种常见的通信,本质是给子组件传入一个function,在子组件里执行完某些方法后,再执行传入的这个回调function,将值传给父组件

parent.component.ts

@Component({
 selector: 'app-child-to-parent',
 templateUrl: './parent.component.html',
 styleUrls: ['./parent.component.css']
})
export class ChildToParentComponent implements OnInit {

 childName: string;
 childNameForInject: string;
 constructor( ) { }
 ngOnInit() {
 }
 showChildName(name: string) {
  this.childName = name;
 }
}

parent.component.html

<div class="panel-body">
 <p>output方式 childText:{{childName}}</p>
 <br>
 <app-output-child (childNameEventEmitter)="showChildName($event)"></app-output-child>
</div>
 child.component.ts
 export class OutputChildComponent implements OnInit {
 // 传入的回调事件
 @Output() public childNameEventEmitter: EventEmitter<any> = new EventEmitter();
 constructor() { }
 ngOnInit() {
 }
 showMyName(value) {
  //这里就执行,父组件传入的函数
  this.childNameEventEmitter.emit(value);
 }
}

注入父组件

这个原理的原因是父,子组件本质生命周期是一样的

export class OutputChildComponent implements OnInit {
 // 注入父组件
 constructor(private childToParentComponent: ChildToParentComponent) { }
 ngOnInit() {
 }
 showMyName(value) {
  this.childToParentComponent.childNameForInject = value;
 }
}

sibling组件 => sibling组件

service

Rxjs

通过service通信

angular中service是单例的,所以三种通信类型都可以通过service,很多前端对单例理解的不是很清楚,本质就是
,你在某个module中注入service,所有这个modul的component都可以拿到这个service的属性,方法,是共享的,所以常在app.moudule.ts注入日志service,http拦截service,在子module注入的service,只能这个子module能共享,在component注入的service,就只能子的component的能拿到service,下面以注入到app.module.ts,的service来演示

user.service.ts

@Injectable()
export class UserService {
 age: number;
 userName: string;
 constructor() { }
}

app.module.ts

@NgModule({
 declarations: [
  AppComponent,
  SiblingAComponent,
  SiblingBComponent
 ],
 imports: [
  BrowserModule
 ],
 providers: [UserService],
 bootstrap: [AppComponent]
})
export class AppModule { }
SiblingBComponent.ts
@Component({
 selector: 'app-sibling-b',
 templateUrl: './sibling-b.component.html',
 styleUrls: ['./sibling-b.component.css']
})
export class SiblingBComponent implements OnInit {
 constructor(private userService: UserService) {
  this.userService.userName = "王二";
 }
 ngOnInit() {
 }
}

SiblingAComponent.ts

@Component({
 selector: 'app-sibling-a',
 templateUrl: './sibling-a.component.html',
 styleUrls: ['./sibling-a.component.css']
})
export class SiblingAComponent implements OnInit {
 userName: string;
 constructor(private userService: UserService) {
 }
 ngOnInit() {
  this.userName = this.userService.userName;
 }
}

通过Rx.js通信

这个是最牛逼的,基于订阅发布的这种流文件处理,一旦订阅,发布的源头发生改变,订阅者就能拿到这个变化;这样说不是很好理解,简单解释就是,b.js,c.js,d.js订阅了a.js里某个值变化,b.js,c.js,d.js立马获取到这个变化的,但是a.js并没有主动调用b.js,c.js,d.js这些里面的方法,举个简单的例子,每个页面在处理ajax请求的时候,都有一弹出的提示信息,一般我会在
组件的template中中放一个提示框的组件,这样很繁琐每个组件都要来一次,如果基于Rx.js,就可以在app.component.ts中放这个提示组件,然后app.component.ts订阅公共的service,就比较省事了,代码如下

首先搞一个alset.service.ts

import {Injectable} from "@angular/core";
import {Subject} from "rxjs/Subject";
@Injectable()
export class AlertService {
 private messageSu = new Subject<string>(); //
 messageObserve = this.messageSu.asObservable();
 private setMessage(message: string) {
  this.messageSu.next(message);
 }
 public success(message: string, callback?: Function) {
  this.setMessage(message);
  callback();
 }
}

sibling-a.component.ts

@Component({
 selector: 'app-sibling-a',
 templateUrl: './sibling-a.component.html',
 styleUrls: ['./sibling-a.component.css']
})
export class SiblingAComponent implements OnInit {
 userName: string;
 constructor(private userService: UserService, private alertService: AlertService) {
 }
 ngOnInit() {
  this.userName = this.userService.userName;
  // 改变alertService的信息源
  this.alertService.success("初始化成功");
 }
}

app.component.ts

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})
export class AppComponent {
 title = 'app';
 message: string;
 constructor(private alertService: AlertService) {
  //订阅alertServcie的message服务
   this.alertService.messageObserve.subscribe((res: any) => {
   this.message = res;
  });
 }
}

这样订阅者就能动态的跟着发布源变化

总结: 以上就是常用的的通信方式,各种场景可以采取不同的方法。希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Angular 2父子组件之间共享服务通信的实现

    前言 如今的前端开发,都朝组件式开发模式靠拢,如果使用目前最流行的前端框架Angular和React开发应用,不可避免地需要开发组件,也就意味着我们需要考虑组件间的数据传递等问题,不过Angular 2已经为我们提供了很好的解决方案. 本文详细介绍了Angular2父子组件共享服务通信的相关内容,父子组件共享同一个服务,利用该服务实现双向通信,下面来看看详细的介绍: 第一步:定义服务 parentService.ts 1).这里用Injectable修饰这个类是一个服务,在其他用到地方只需要注入

  • 详解Angular2组件之间如何通信

    组件之间的共享可以有好几种方式 父->子 input 方式 import {Component,Input} from 'angular2/core'; @Component({ selector: 'child', template: ` <h2>child {{content}}</h2> ` }) class Child { @Input() content:string; } @Component({ selector: 'App', directives: [Chi

  • Angular2 父子组件通信方式的示例

    Angular2官方文档对组件交互这块有详细的介绍-->文档--组件之间的交互.按文档介绍,组件间交互的方式一共有4种,包括: 通过输入型绑定把数据从父组件传到子组件(@Input decoration):子组件暴露一个EventEmitter属性(@Output decoration),当事件发生时,利用该属性emits向父组件发射事件. 父组件与子组件通过本地变量互动.(# var) 父组件调用@ViewChild. 父组件和子组件通过服务来通讯. 我在这里只总结.详细介绍3种我在项目中使用

  • Angular2 组件通信的实例代码

    1. 组件通信 我们知道Angular2应用程序实际上是有很多父子组价组成的组件树,因此,了解组件之间如何通信,特别是父子组件之间,对编写Angular2应用程序具有十分重要的意义,通常来讲,组件之间的交互方式主要有如下几种: 使用输入型绑定,把数据从父组件传到子组件 通过 setter 拦截输入属性值的变化 使用 ngOnChanges 拦截输入属性值的变化 父组件监听子组件的事件 父组件与子组件通过本地变量互动 父组件调用 ViewChild 父组件和子组件通过服务来通讯 本文会通过讲解着几

  • Angular2 父子组件数据通信实例

    如今的前端开发,都朝组件式开发模式靠拢,如果使用目前最流行的前端框架Angular和React开发应用,不可避免地需要开发组件,也就意味着我们需要考虑组件间的数据传递等问题,不过Angular 2已经为我们提供了很好的解决方案. 父组件和子组件 接触过面向对象编程的开发者肯定不会对父子关系陌生,在Angular 2中子组件存在于父组件"体内",并且父子组件可以通过一些渠道进行通讯. 父组件向子组件传入数据 – @Input 当我们着手开始开发一个组件时,第一件想到的应该就是为其传入数据

  • Angularjs2不同组件间的通信实例代码

    AngualrJs2官方方法是以@Input,@Output来实现组件间的相互传值,而且组件之间必须父子关系,下面给大家提供一个简单的方法,实现组件间的传值,不仅仅是父子组件,跨模块的组件也可以实现传值 /** *1.定义一个服务,作为传递参数的媒介 */ @Injectable() export class PrepService{ //定义一个属性,作为组件之间的传递参数,也可以是一个对象或方法 profileInfo: any; } /** *2.传递参数的组件,我这边简单演示,直接就在构

  • angular4 共享服务在多个组件中数据通信的示例

    应用场景,不同组件中操作统一组数据,不论哪个组件对数据进行了操作,其他组件中立马看到效果.这样他们就要共用一个服务实例,是本次的重点,如果不同实例,那么操作的就不是同一组数据,那么就不会有这样的效果,想实现共用服务实例,就是在所有父组件中priviates:[]中引入这个组件,子组件中不需要再次引入,那么他们都是用的父组件中的服务实例. 1.公用服务 import {Injectable} from "@angular/core"; @Injectable() export class

  • angular中不同的组件间传值与通信的方法

    本文主要介绍angular在不同的组件中如何进行传值,如何通讯.主要分为父子组件和非父子组件部分. 父子组件间参数与通讯方法 使用事件通信(EventEmitter,@Output): 场景:可以在父子组件之间进行通信,一般使用在子组件传递消息给父组件: 步骤: 子组件创建事件EventEmitter对象,使用@output公开出去: 父组件监听子组件@output出来的方法,然后处理事件. 代码: // child 组件 @Component({ selector: 'app-child',

  • angular 组件通信的几种实现方式

    单页面应用组件通信有以下几种,这篇文章主要讲 Angular 通信 父组件 => 子组件 子组件 => 父组件 组件A = > 组件B 父组件 => 子组件 子组件 => 父组件 sibling => sibling @input @output setters (本质上还是@input) 注入父组件 ngOnChanges() (不推荐使用) 局部变量 @ViewChild() service service service Rxjs的Observalbe Rxjs的

  • Vue.js组件通信的几种姿势

    写在前面 因为对Vue.js很感兴趣,而且平时工作的技术栈也是Vue.js,这几个月花了些时间研究学习了一下Vue.js源码,并做了总结与输出. 文章的原地址: https://github.com/answershuto/learnVue . 在学习过程中,为Vue加上了中文的注释 https://github.com/answershuto/learnVue/tree/master/vue-src ,希望可以对其他想学习Vue源码的小伙伴有所帮助. 可能会有理解存在偏差的地方,欢迎提issu

  • vue实现组件通信的八种方法实例

    目录 1.props 父组件--->子组件通信 2.$emit 子组件--->父组件传递 3.bus(事件总线) 兄弟组件通信 4.$parent.$children 直接访问组件实例 5.$refs 6.provide/inject(提供/注入) 多组件或深层次组件通信 7.slot(slot-scope作用域插槽) 子元素-->父元素(类似于通信) 8.vuex状态管理 总结 对于vue来说,组件之间的消息传递是非常重要的,下面是我对组件之间消息传递的常用方式的总结 1.props

  • android实现线程间通信的四种常见方式

    1,通过Handler机制 主线程中定义Handler,子线程发消息,通知Handler完成UI更新,Handler对象必须定义在主线程中,如果是多个类直接互相调用,就不是很方便,需要传递content对象或通过接口调用. 另外Handler机制与Activity生命周期不一致的原因,容易导致内存泄漏,不推荐使用. private void one() { handler=new Handler(){ @Override public void handleMessage(Message msg

  • 分享Vue组件传值的几种常用方式(一)

    目录 前言 第一种:父向子传值 新建文件导入结构 引入 注册 使用子组件 子组件内部代码完善 父组件内部代码完善 操作main.js文件 思路总结 前言 大家好,这个系列我们来讲解一下vue组件传值的几种常见方法和逻辑链路.最常见的vue组件传值分为三种,第一种是父向子传值,第二种是子向父传值,第三种是兄弟组件之间的传值,下面我们先就第一种情况来进行分析和编写. 第一种:父向子传值 父向子传值意思就是要把父组件里的值传递给子组件,方法是在子组件内部自定义一个props属性,通过props属性来完

  • 详解vue组件通信的三种方式

    1. 第一种方式就是官方推荐的 官方推荐方式 有时候两个组件也需要通信(非父子关系).在简单的场景下,可以使用一个空的 Vue 实例作为中央事件总线. 本质是通过派发事件然后监听事件从而更改值,(父子组件通信也可用这个方式,但是不同的一点就是父子组件通信的时候可以不用一个空的Vue实例来做中转,这种方式我这里就不做演示的了,因为我的题目是非父子通信) 空的Vue实例 bus import Vue from 'vue' const bus = new Vue() export default bu

  • 关于react中组件通信的几种方式详解

    前言 刚入门React可能会因为React的单向数据流的特性而遇到组件间沟通的麻烦,下面这篇文章就来给大家详细介绍下,在开始之前先来看一张图: react组件通信 需要组件之进行通信的几种情况 父组件向子组件通信 子组件向父组件通信 跨级组件通信 没有嵌套关系组件之间的通信 1. 父组件向子组件通信 React数据流动是单向的,父组件向子组件通信也是最常见的;父组件通过props向子组件传递需要的信息 Child.jsx import React from 'react'; import Pro

  • Vue组件通信的四种方式汇总

    前言 众所周知vue是一种mvvm框架,它相对于jquery可能比较大的差异点之一就在于组件之间的通信了.本文重点是梳理了前两个,父子组件通信和eventBus通信,我觉得Vue文档里的说明还是有一些简易,我自己第一遍是没看明白. 父子组件的通信 非父子组件的eventBus通信 利用本地缓存实现组件通信 Vuex通信 第一种通信方式:父子组件通信 父组件向子组件传递数据 父组件一共需要做4件事 1.import son from './son.js' 引入子组件 son 2.在componen

  • vue中组件通信的八种方式(值得收藏!)

    前言 之前写了一篇关于vue面试总结的文章, 有不少网友提出组件之间通信方式还有很多, 这篇文章便是专门总结组件之间通信的 vue是数据驱动视图更新的框架, 所以对于vue来说组件间的数据通信非常重要,那么组件之间如何进行数据通信的呢? 首先我们需要知道在vue中组件之间存在什么样的关系, 才更容易理解他们的通信方式, 就好像过年回家,坐着一屋子的陌生人,相互之间怎么称呼,这时就需要先知道自己和他们之间是什么样的关系. vue组件中关系说明: 如上图所示, A与B.A与C.B与D.C与E组件之间

  • Vue组件通信的几种实现方法

    组件的通信 一般常见的组件之间的通信有以下几种情况,A和B,B和C,B和D之间都是父子关系,C和D之间是兄弟组件关系. 常用的通信手段有两种: 1.ref:给元素或组件注册引用信息 2.children:访问父级组件和子组件的实例. 这两种方式都是直接通过实例的方式获取的方式.示例如下: //comA组件A export default { data () { return { title: '测试通信' } }, methods: { sayHello () { window.alert('你

随机推荐