在这里,我想在同一个父级的两个组件之间进行通信。基本上,我想将数据从一个组件传递到另一个组件。
第一个组件.ts
constructor(
private service: service1,
private serve: service2,
) {}
ngOnInit() {
this.service.getUser().subscribe((data) => {
this.serve.setAccount("1", "apple");
this.serve.setEnvironment("Happy");
})
}
第二组件.ts
constructor(private usingService : service2) { }
ngOnInit() {
this.Account = this.serve.getAccount();
this.environmentDetails = this.serve.getEnvironment();
}
我需要从 firstComponent 检索数据到 second.here 第一个组件在第二个 component.soo 之后加载,第一个组件设置的数据稍后在图片中。
尝试使用 rxjs.but 的主题,我们如何在本示例的 firstComponent.ts 中使用主题?
我如何在这两个组件之间进行通信,因为它们是彼此的 sibling ?请帮助
最佳答案
您可以使用 @Input()
@Output()
带有 EventEmitter
的装饰器.父组件将通过绑定(bind)设置子组件的数据。 child 将向 parent 发送新数据并重置 child 收到的数据。
父组件.ts
@Component({
selector: 'app-parent',
template: `
<app-first-component
[data]="data" (onData)="updateData($event)"></app-first-component>
<app-second-component
[data]="data" (onData)="updateData($event)"></app-second-component>
`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
public data: any;
constructor() {}
updateData(event) {
this.data = event;
}
}
first.component.ts
@Component({
selector: 'app-first',
templateUrl: './first.component.html',
styleUrls: ['./first.component.css']
})
export class FirstComponent implements {
@Input()
public data: any
@Output()
public onData: EventEmitter<any> = new EventEmitter<any>();
constructor() { }
updateData(data) {
//send data back to parent
//data could be coming from a service/async http request as well.
this.onData.emit(data)
}
}
第二个组件.ts
@Component({
selector: 'app-second',
templateUrl: './second.component.html',
styleUrls: ['./second.component.css']
})
export class SecondComponent implements {
@Input()
public data: any
@Output()
public onData: EventEmitter<any> = new EventEmitter<any>();
constructor() { }
updateData(data) {
//send data back to parent
//data could be coming from a service/async http request as well.
this.onData.emit(data)
}
}
关于angular - 使用 Angular 7 在两个同级组件之间进行通信的方法,而无需为两者使用公共(public)服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54972439/