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 inplemented');
   }
   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 AppParentComponent 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":"Jack"}]

(传递方式二:router.navigate):

this.router.navigate['/exmapledetail',id]
this.router.navigate['/exampledetail',{queryParams:{'name':'Jack'}}]

(传递方式三:router.navigateByUrl):

this.router.navigateByUrl('/exampledetail/id');
this.router.navigateByUrl('/exampledetail',{queryParams:{'name':'Jack'}});

 

传参方传递参数以后,接收方有2中接收方式如下:
(接收方式一: snapshot)

import { ActivateRouter } from '@angular/router';
export class ExampleDetailComponent implements 	OnInit {
	public data : any;
	constructor(public route:ActivateRouter ){};
	ngOnInit(){
		this.data = this.router.snapshot.params['id'];
	};
}

(接收方式一: queryParams)

import { ActivateRouter } from '@angular/router';
public data : any;
constructor(public route:ActivateRouter){};
ngOnInit(){
	this.activateRouter.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);
   // 组件A接收消息
   const b = this.message.getMessage();
   }
}

// 组件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();
   	//组件B发送信息
   	this.message.sendMessage(5);
   }
}

消息服务模块

场景:这里涉及到一个项目,里面需要实现的是所有的组件都能进行通讯,或者是一个组件与多个组件进行通讯,且不能通过路由进行传参
设计方式:

  • 使用RxJs,定义一个服务模块MessageService,所有的组件都能注册该服务
  • 需要传递数据的组件,调用该服务对应的方法
  • 需要接受数据的组件,调用该服务接收数据的方法,获得一个subscription对象,然后监听信息
  • 每一个使用该服务的组件,在Destroy的时候,需要this.subscription.unsubscribe()
    代码:
// 消息中转服务
@Injectable()
export class MessageService {
   private subject = new Subject<any>();
   
   /**
   *content 模块里进行信息传输,类似广播@param type 发送的信息类型
   * 1-你的信息1
   * 2-你的信息2
   * 3-你的信息3
   */
   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().subscrible(
   		msg => {
   			// 根据 msg 来处理你的业务逻辑
   		})
   }
   
   // 调用该服务发送信息
   send():void {
   	this.message.sendMessage('我发消息了,你们接收下')
   }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值