angular中不同的组件间传值与通信的方法(2)
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的时候,需要
