2017-08-17 29 views
0

这是一种很难说出一个单行的问题,但这里是一个更详细的解释:如何在由另一个组件替换并返回到Angular 2的组件之间传递数据?

假设你有,你通过一些过滤器过滤rocketships的画面,让我们称之为F.过滤器可任何东西 - 单选按钮,输入字段或其他。你有一个“显示”按钮,根据过滤器的设置呈现网格中的一些数据。

在过滤器中,有一个“选择模型”按钮。

当你点击这个选择模型按钮时,它会将你带到另一个屏幕,在那里你有另一组字段,就像一个大功能,可以让你确定火箭模型。当你点击一个说'OK'的按钮时,它需要返回到第一个功能并发送你选择的作为火箭模型的数据。

如果还有另外一个级别,并且当你选择了火箭模型时,你将不得不移动到另一个功能来选择火箭飞船idontknowwhat?

你将如何去在Angular中实现这个功能?我应该使用路由器,弹出窗口还是其他?

+0

'https:// stackoverflow.com/a/45668262/2708210'可能重复# –

回答

1

在组件之间传递数据被另一个组件取代,我假设有一个数据可以被多个组件读取和修改。要达到此目的,您可以使用router,在angular servicedependency injectionbehavior subjectsubscription的帮助下。

首先创建一个angular service与behaviorSubject属性作为数据:

@Injectable() 
export class DataService() 
{ 
    public data: Subject<any> = new BehaviorSubject<any>(null); 

    changeData(newData: any) { 
    this.data.next(newData); // this will update the value of the `data` with `newData`, and any component which subscribe to `data` will get the updated value of `data`. 
    } 
} 

一种可注射的服务能够保持数据的同时,从用户到其他组件的组件跳跃。下一步是将此服务注入需要数据的组件。让我们ComponentAComponentB需要的数据。例如:

@Component({ 
    selector: 'component-a' 
    providers: [DataService], 
    templateUrl: `component-a.html` 
)} 

export class ComponentA { 
    constructor(private dataService: DataService) { 
    this.dataService.data.subscribe((value) => { 
     // here, component A able to always get the updated value of the data when its value is changed. 
    }); 
    } 
} 

而对于以componentB,让我们说这个部件必须更换(或更新)数据的能力:

@Component({ 
    selector: 'component-b' 
    providers: [DataService], 
    templateUrl: `component-b.html` 
)} 

export class ComponentB { 
    constructor(private dataService: DataService) { 
    this.dataService.data.subscribe((value) => { 
     // here, component B able to always get the updated value of the data when its value is changed. 
    }); 
    } 

    changeData(newData: any) { 
    this.dataService.changeData(newData); // this call will update the value of the data which DataService keeps, therefore when user jump to ComponentA, ComponentA will retrieve the updated value from `this.dataService.data`'s subscription 
    } 
} 

现在,当您使用路由器这两个组件的路由,每当用户导航到一个组件,该组件将获得最新的数据值。

+0

非常感谢您的回答! –

相关问题