搜索
首页头条实例详解angular中不同的组件间传值与通信的方法

本文主要介绍了angular中不同的组件间传值与通信的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧,希望能帮助到大家。

本文主要介绍angular在不同的组件中如何进行传值,如何通讯。主要分为父子组件和非父子组件部分。

父子组件间参数与通讯方法

使用事件通信(EventEmitter,@Output):

场景:可以在父子组件之间进行通信,一般使用在子组件传递消息给父组件;

步骤:

  1. 子组件创建事件EventEmitter对象,使用@output公开出去;

  2. 父组件监听子组件@output出来的方法,然后处理事件。

代码:


 // child 组件
  @Component({
   selector: 'app-child',
   template: '',
   styles: [``]
  })
  export class AppChildComponent implements OnInit {
   @Output() onVoted: EventEmitter<any> = new EventEmitter();
   ngOnInit(): void {
    this.onVoted.emit(1);
   }
  }
  // parent 组件
  @Component({
   selector: &#39;app-parent&#39;,
   template: `
    <app-child (onVoted)="onListen($event)"></app-child>
   `,
   styles: [``]
  })
  export class AppParentComponent implements OnInit {
   ngOnInit(): void {
    throw new Error(&#39;Method not implemented.&#39;);
   }
   onListen(data: any): void {
    console.log(&#39;TAG&#39; + &#39;---------->>>&#39; + data);
   }
  }

使用@ViewChild和@ViewChildren:

场景:一般用于父组件给子组件传递信息,或者父组件调用子组件的方法;

步骤:

  1. 父组件里面使用子组件;

  2. 父组件里面使用@ViewChild获得子组件对象。

  3. 父组件使用子组件对象操控子组件;(传递信息或者调用方法)。

代码:


// 子组件
@Component({
 selector: &#39;app-child&#39;,
 template: &#39;&#39;,
 styles: [``]
})
export class AppChildComponent2 implements OnInit {
  data = 1;
  ngOnInit(): void {
 }
 getData(): void {
  console.log(&#39;TAG&#39; + &#39;---------->>>&#39; + 111);
 }
}
// 父组件
@Component({
 selector: &#39;app-parent2&#39;,
 template: `
  <app-child></app-child>
 `,
 styles: [``]
})
export class AppParentComponent2 implements OnInit {
 @ViewChild(AppChildComponent2) child: AppChildComponent2;
 ngOnInit(): void {
  this.child.getData(); // 父组件获得子组件方法
  console.log(&#39;TAG&#39;+&#39;---------->>>&#39;+this.child.data);// 父组件获得子组件属性
 }
}

非父子组件参数传递与通讯方法

通过路由参数

场景:一个组件可以通过路由的方式跳转到另一个组件 如:列表与编辑

步骤:

  1. A组件通过routerLink或router.navigate或router.navigateByUrl进行页面跳转到B组件

  2. B组件接受这些参数

此方法只适用于参数传递,组件间的参数一旦接收就不会变化

代码

传递方式

routerLink


<a routerLink=["/exampledetail",id]></a>

routerLink=["/exampledetail",{queryParams:object}]

routerLink=["/exampledetail",{queryParams:&#39;id&#39;:&#39;1&#39;,&#39;name&#39;:&#39;yxman&#39;}];

router.navigate


this.router.navigate([&#39;/exampledetail&#39;,id]);
this.router.navigate([&#39;/exampledetail&#39;],{queryParams:{&#39;name&#39;:&#39;yxman&#39;}});

router.navigateByUrl


this.router.navigateByUrl(&#39;/exampledetail/id&#39;);
this.router.navigateByUrl(&#39;/exampledetail&#39;,{queryParams:{&#39;name&#39;:&#39;yxman&#39;}});

传参方传参之后,接收方2种接收方式如下:

snapshot


import { ActivateRoute } from &#39;@angular/router&#39;;
public data: any;
export class ExampledetailComponent implements OnInit { 
  constructor( public route: ActivateRoute ) { };
  ngOnInit(){
    this.data = this.route.snapshot.params[&#39;id&#39;];
  };
}

queryParams


import { ActivateRoute } from &#39;@angular/router&#39;;
export class ExampledetailComponent implements OnInit { 
  public data: any;
  constructor( public activeRoute:ActivateRoute ) { };
  ngOnInit(){
    this.activeRoute.queryParams.subscribe(params => {
    this.data = params[&#39;name&#39;];
  });
};

使用服务Service进行通信,即:两个组件同时注入某个服务

场景:需要通信的两个组件不是父子组件或者不是相邻组件;当然,也可以是任意组件。

步骤:

  1. 新建一个服务,组件A和组件B同时注入该服务;

  2. 组件A从服务获得数据,或者想服务传输数据

  3. 组件B从服务获得数据,或者想服务传输数据。

代码:


  // 组件A
  @Component({
   selector: &#39;app-a&#39;,
   template: &#39;&#39;,
   styles: [``]
  })
  export class AppComponentA implements OnInit {
   constructor(private message: MessageService) {
   }
   ngOnInit(): void {
    // 组件A发送消息3
    this.message.sendMessage(3);
    const b = this.message.getMessage(); // 组件A接收消息;
   }
  }
  // 组件B
  @Component({
   selector: &#39;app-b&#39;,
   template: `
    <app-a></app-a>
   `,
   styles: [``]
  })
  export class AppComponentB implements OnInit {
   constructor(private message: MessageService) {
   }
   ngOnInit(): void {
    // 组件B获得消息
    const a = this.message.getMessage();
    this.message.sendMessage(5); // 组件B发送消息
   }
  }

消息服务模块

场景:这里涉及到一个项目,里面需要实现的是所有组件之间都有可能通信,或者是一个组件需要给几个组件通信,且不可通过路由进行传参。

设计方式:

  1. 使用RxJs,定义一个服务模块MessageService,所有的信息都注册该服务;

  2. 需要发消息的地方,调用该服务的方法;

  3. 需要接受信息的地方使用,调用接受信息的方法,获得一个Subscription对象,然后监听信息;

  4. 当然,在每一个组件Destory的时候,需要


this.subscription.unsubscribe();

代码:


  // 消息中专服务
  @Injectable()
  export class MessageService {
   private subject = new Subject<any>();
   /**
   * content模块里面进行信息传输,类似广播
   * @param type 发送的信息类型
   *    1-你的信息
   *    2-你的信息
   *    3-你的信息
   *    4-你的信息
   *    5-你的信息
   */
   sendMessage(type: number) {
    console.log(&#39;TAG&#39; + &#39;---------->>>&#39; + type);
    this.subject.next({type: type});
   }
   /**
   * 清理消息
   */
   clearMessage() {
    this.subject.next();
   }
   /**
   * 获得消息
   * @returns {Observable<any>} 返回消息监听
   */
   getMessage(): Observable<any> {
    return this.subject.asObservable();
   }
  }
  // 使用该服务的地方,需要注册MessageService服务;
  constructor(private message: MessageService) {
  }
  // 消息接受的地方;
  public subscription: Subscription;
  ngAfterViewInit(): void {
    this.subscription = this.message.getMessage().subscribe(msg => {
     // 根据msg,来处理你的业务逻辑。
    })
   }

   // 组件生命周期结束的时候,记得注销一下,不然会卡;
   ngOnDestroy(): void {
    this.subscription.unsubscribe();
   }

   // 调用该服务的方法,发送信息;
   send():void {
    this.message.sendMessage(‘我发消息了,你们接受下&#39;); // 发送信息消息
   }

这里的MessageService,就相当于使用广播机制,在所有的组件之间传递信息;不管是数字,字符串,还是对象都是可以传递的,而且这里的传播速度也是很快的。

相关推荐:

实例讲解nodejs中express获取get和post传值及session验证的方法

两种vue父组件向子组件动态传值的方法分享

详解fetch的使用方法及如何接收JS传值

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
4 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。