我正在处理角5,我在父组件上有一个对象数组,需要在子组件中显示,如果在该对象数组中有任何值被更改,我希望父组件的值也应该被更新。现在我的问题是,角提供了3种方式的组件集成。
哪一个更有效率?在我的情况下,哪一种方法最好?还是一般的父子数据共享?
发布于 2019-03-18 06:59:39
对更新的数据句柄使用服务方法,下面是代码
创建一个data-sharing.service.ts文件
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataSharingService {
private dataSource = new BehaviorSubject<any>('null');
currentData = this.dataSource.asObservable();
private activeStateData = new BehaviorSubject<any>('null');
currentActive = this.activeStateData.asObservable();
constructor() { }
changeData(data:any){
this.dataSource.next(data);
}
aciveState(state:string){
this.activeStateData.next(state);
}
}来自父组件的
constructor( private alertService: AlertService)
add() {
let yourSharingData = null;
this.dataService.changeData(yourSharingData );
this.router.navigate(["/path-to-your-child"]);
}来自子组件的订阅服务
this.dataService.currentData.subscribe(res => {
console.log(res);
})发布于 2019-03-18 06:49:21
<comp1>)在另一个组件(<comp2>)的模板中使用。使用@Input @Output- as both components will be in a parent-child relationship
- simple and best to exchange data to/from the child component
<comp1>, <comp2>)在第三个成分的温带(<comp3>)中使用。使用服务(只适用于小型应用程序,不推荐用于大型应用程序)- both components (comp1, comp2) are not directly related
- as two components are not in parent-child relation, @Input @Output wont work here
- Alternatively, you can **also use ngrx/store library for large apps** (state management)
发布于 2019-03-18 06:57:35
让我演示一下..。
@Input()和@Output()通常用于在父组件和子组件之间传递特定变量。
其中,@Input()过去将变量从父变量传递给子变量,而@Output()则将变量从子变量传递给父变量。@ViewChild()用于在父组件中获得子组件的控制。
使用它时,可以将子组件捕获为对象,因此可以调用其函数、编辑其变量等等。parent和child组件之间的变量。
从我的观点来看,您不应该使用服务将数据从parent传递给child,反之亦然;因为如果您两次使用一个子组件的多个子组件,您将面临很多问题。https://stackoverflow.com/questions/55215757
复制相似问题