Angular 5父子数据共享 [英] Angular 5 parent child data sharing

查看:65
本文介绍了Angular 5父子数据共享的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究角度5. 我在父组件上有一个对象数组,需要在子组件中显示.如果该对象数组中的任何值被更改,我希望父组件的值也应更新. 现在我的问题是 Angular提供了3种方法来进行分量求逆.

I'm working on angular 5. I have one array of objects on parent component which I need to show in child component, If any value gets changed in that array of object, I want parent component's value should also be updated. Now My question is, Angular provides 3 ways for component intrection.

  1. @Input @output 装饰器
  2. @viewchild 装饰器
  3. 使用服务
  1. @Input @output decorators
  2. @viewchild decorator
  3. Using Services

哪个更高效? 就我而言,哪种方法最好?或一般来说,父子数据共享?

Which One is more Efficient? Which is best approach In my case? or In general parent child data sharing?

推荐答案

使用服务方法更新数据句柄,以下是代码

Use service approach for updated data handles, following is code

创建一个data-sharing.service.ts文件

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

@Injectable({
  providedIn: 'root'
})
export class DataSharingService {

  private dataSource  = new BehaviorSubject<any>('null');
  currentData = this.dataSource.asObservable();


  private activeStateData  = new BehaviorSubject<any>('null');
  currentActive = this.activeStateData.asObservable();
  constructor() { }

  changeData(data:any){
    this.dataSource.next(data);
  }

  aciveState(state:string){
    this.activeStateData.next(state);
  }    
}

来自父组件

constructor( private alertService: AlertService)
  add() {
    let yourSharingData = null;
    this.dataService.changeData(yourSharingData );
    this.router.navigate(["/path-to-your-child"]);
  }

来自子组件的订阅服务

this.dataService.currentData.subscribe(res => {
console.log(res);
})

这篇关于Angular 5父子数据共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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