看起来您正在寻找重定向到这些组件,您可以做的是在组件 1 上设置一个事件发射器,单击时会将数据发送到父组件(所有 3 个组件)。然后在父级中捕获发射,并将其分配给传递给其他组件的数据。
组件1
import { Component, EventEmitter, Output } from '@angular/core';
import { Router } from '@angular/router';
@Component(...)
export class Component1 {
@Output() redirect:EventEmitter<any> = new EventEmitter();
data:any = {text: "example"};
constructor(private router:Router){}
changeComponent(url:string){
this.redirect.emit(data);//emits the data to the parent
this.router.navigate([url]);//redirects url to new component
}
}
组件2和组件3
import { Component, Input } from '@angular/core';
@Component(...)
export class Component2 {
@Input() data:any;
}
父母
import { Component } from '@angular/core';
@Component(...)
export class Parent {
parentData:any;
}
父.html
<component1 (redirect)="parentData=$event"></component1>
<component2 [data]="parentData"></component2>
<component3 [data]="parentData"></component3>
如果您没有父级,另一种选择是拥有一个服务,您将其注入每个父级,然后将接收器挂钩到 OnInit 生命周期挂钩。这是可行的,因为如果在共享模块的提供者中,服务是单例的。
服务
import { Injectable } from '@angular/core';
@Injectable()
export class SharingService{
private data:any = undefined;
setData(data:any){
this.data = data;
}
getData():any{
return this.data;
}
}
组件1
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { SharingService } form './sharing.service';
@Component(...)
export class Component1 {
data:any = {text: "example"};
constructor(private router:Router,
private sharingService:SharingService){}
changeComponent(url:string){
this.sharingService.setData(this.data);
this.router.navigate([url]);//redirects url to new component
}
}
组件2和组件3
import { Component, OnInit } from '@angular/core';
import { SharingService } form './sharing.service';
@Component(...)
export class Component2 implements OnInit{
data:any;
constructor(private router:Router,
private sharingService:SharingService){}
ngOnInit(){
this.data = this.sharingService.getData();
}
}
确保将其添加到模块的 providers 数组中。
模块
import { SharingService } from './sharing.service';
...
@NgModule({
...
providers: [ SharingService ]
})