您好,欢迎访问一九零五行业门户网

angular组件间传值与通信使用详解

这次给大家带来angular组件间传值与通信使用详解,angular组件间传值与通信的注意事项有哪些,下面就是实战案例,一起来看一下。
本文主要介绍angular在不同的组件中如何进行传值,如何通讯。主要分为父子组件和非父子组件部分。
父子组件间参数与通讯方法
使用事件通信(eventemitter,@output):
场景:可以在父子组件之间进行通信,一般使用在子组件传递消息给父组件;
步骤:
子组件创建事件eventemitter对象,使用@output公开出去;
父组件监听子组件@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: 'app-parent',    template: `     <app-child (onvoted)="onlisten($event)"></app-child>    `,    styles: [``]   })   export class appparentcomponent implements oninit {    ngoninit(): void {     throw new error('method not implemented.');    }    onlisten(data: any): void {     console.log('tag' + '---------->>>' + data);    }   }
使用@viewchild和@viewchildren:
场景:一般用于父组件给子组件传递信息,或者父组件调用子组件的方法;
步骤:
父组件里面使用子组件
父组件里面使用@viewchild获得子组件对象。
父组件使用子组件对象操控子组件;(传递信息或者调用方法)。
代码:
// 子组件 @component({  selector: 'app-child',  template: '',  styles: [``] }) export class appchildcomponent2 implements oninit {   data = 1;   ngoninit(): void {  }  getdata(): void {   console.log('tag' + '---------->>>' + 111);  } } // 父组件 @component({  selector: 'app-parent2',  template: `   <app-child></app-child>  `,  styles: [``] }) export class appparentcomponent2 implements oninit {  @viewchild(appchildcomponent2) child: appchildcomponent2;  ngoninit(): void {   this.child.getdata(); // 父组件获得子组件方法   console.log('tag'+'---------->>>'+this.child.data);// 父组件获得子组件属性  } }
非父子组件参数传递与通讯方法
通过路由参数
场景:一个组件可以通过路由的方式跳转到另一个组件 如:列表与编辑
步骤:
a组件通过routerlink或router.navigate或router.navigatebyurl进行页面跳转到b组件
b组件接受这些参数
此方法只适用于参数传递,组件间的参数一旦接收就不会变化
代码
传递方式
routerlink
<a routerlink=["/exampledetail",id]></a> routerlink=[/exampledetail,{queryparams:object}] routerlink=[/exampledetail,{queryparams:'id':'1','name':'yxman'}];
router.navigate
this.router.navigate(['/exampledetail',id]); this.router.navigate(['/exampledetail'],{queryparams:{'name':'yxman'}});
router.navigatebyurl
this.router.navigatebyurl('/exampledetail/id'); this.router.navigatebyurl('/exampledetail',{queryparams:{'name':'yxman'}});
传参方传参之后,接收方2种接收方式如下:
snapshot
import { activateroute } from '@angular/router'; public data: any; export class exampledetailcomponent implements oninit {    constructor( public route: activateroute ) { };   ngoninit(){     this.data = this.route.snapshot.params['id'];   }; }
queryparams
import { activateroute } from '@angular/router'; export class exampledetailcomponent implements oninit {    public data: any;   constructor( public activeroute:activateroute ) { };   ngoninit(){     this.activeroute.queryparams.subscribe(params => {     this.data = params['name'];   }); };
使用服务service进行通信,即:两个组件同时注入某个服务
场景:需要通信的两个组件不是父子组件或者不是相邻组件;当然,也可以是任意组件。
步骤:
新建一个服务,组件a和组件b同时注入该服务;
组件a从服务获得数据,或者想服务传输数据
组件b从服务获得数据,或者想服务传输数据。
代码:
// 组件a   @component({    selector: 'app-a',    template: '',    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: 'app-b',    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发送消息    }   }
消息服务模块
场景:这里涉及到一个项目,里面需要实现的是所有组件之间都有可能通信,或者是一个组件需要给几个组件通信,且不可通过路由进行传参。
设计方式:
使用rxjs,定义一个服务模块messageservice,所有的信息都注册该服务;
需要发消息的地方,调用该服务的方法;
需要接受信息的地方使用,调用接受信息的方法,获得一个subscription对象,然后监听信息;
当然,在每一个组件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('tag' + '---------->>>' + 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(‘我发消息了,你们接受下'); // 发送信息消息    }
这里的messageservice,就相当于使用广播机制,在所有的组件之间传递信息;不管是数字,字符串,还是对象都是可以传递的,而且这里的传播速度也是很快的。
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
js封装操作class步奏详解
标签selected=selected属性失效如何处理
以上就是angular组件间传值与通信使用详解的详细内容。
其它类似信息

推荐信息