• Angular非父子组件参数传递与通讯-转载


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

    原文地址:https://blog.csdn.net/weixin_43194434/article/details/82850083
    通过路由参数
    场景:一个组件可以通过路由的方式跳转到另一个组件,如:列表与编辑
    步骤:

    • A组件通过routerLink 或者 router.navigate 或者 router.navigateByUrl 进行页面跳转到B组件
    • B 组件接收这些参数

    注意此处路由配置上记得给跳转到B的路由上加上id,如下示例:

    {path:'edit/:id',component:EditComponent},
    

    [*] 此方法是适用于参数传递,组件间的参数一旦接收就不会变化
    代码:

    传参方:
    (传递方式一: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 { ActivateRoute } from '@angular/router';
    public data : any;
    constructor(public route:ActivateRoute){};
    ngOnInit(){
    	this.activateRoute.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('我发消息了,你们接收下')
       }
    }
    

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

    由于无法解释的神圣旨意,我们徒然地到处找你;你就是孤独,你就是神秘,比恒河或者日落还要遥远。。。。。。
  • 相关阅读:
    移动端web页面使用position:fixed问题
    登录的一些心得
    响应式网页设计
    xss(跨站脚本攻击),crsf(跨站请求伪造),xssf
    HTML5 离线功能介绍
    webapp开发经验和资料
    学习Java,值得你留意的问题(1)更名为《学习Java,容易被你忽略的小细节(1)》
    Python下搜索文件
    从百度地图API接口批量获取地点的经纬度
    获取代理IP地址(BeautifulSoup)
  • 原文地址:https://www.cnblogs.com/momoli/p/14003464.html
Copyright © 2020-2023  润新知