【问题标题】:Angular 8.0 Data share among component and serviceAngular 8.0 组件和服务之间的数据共享
【发布时间】:2020-06-18 16:53:12
【问题描述】:

我正在努力实现手动表单的自动化。我是角度的新手。

我在 app.component 中有一个步进控件,有 5 个步骤。我创建了 5 个组件并在每个步进器中放置了一个。

<mat-step label="Start">
    <app-project-location></app-project-location>            
</mat-step>    
<mat-step [stepControl]="licensedContractorFormGroup" label="Property Owner Information">
    <app-property-owner></app-property-owner>      
</mat-step>
<mat-step [stepControl]="licensedContractorFormGroup" label="Project In Charge">
    <app-project-in-change-details></app-project-in-change-details>
</mat-step>

上面的每个内部组件都有导航到previousnext 的按钮。

当我填写&lt;app-project-location&gt; 表单并提交下一步时,此表单接受表单输入,调用调用API 的服务,并返回填写下一个组件表的数据。

问题:

如何将表单数据从这个组件传递到另一个没有父子关系的组件?

我调用了该服务,它返回一个 JSON 对象,我怎样才能让它作为 observables 返回?

【问题讨论】:

  • robferguson.org/blog/2017/08/31/… 查看Angular Sibling Component Communication。我会为此使用Ngrx/redux,因为如果你继续重复使用这种模式,它会变得复杂。

标签: angular


【解决方案1】:

首先,如果一个非常好的选择为每个步骤使用一个组件。

那么,正如@AliF50 告诉你的,你应该检查一下这个link

所以,为了简短起见:

1) 将你想要在你的 5 个组件之间共享的所有全局变量放在包含步进器的组件的.component.ts 中。

2) 使用子级(5 个组件)中的Output 事件通知父级(包含步进器的组件)并向其发送数据。

3) 父级将根据收到的事件(来自步骤 1、步骤 2 等),然后使用 Input 属性设置每个子级的变量。

【讨论】:

    【解决方案2】:

    你可以像这样使用 observable:

    服务

    private message: Subject<Your_Data_Type>;
    
    constructor() {
        this.message = new Subject<Your_Data_Type>();
    
        // set new value for variable and emit that
        this.message.next(new_value);
      }
    
    public getMessage(): Observable<Your_Data_Type> {
        return this.message.asObservable();
      }
    

    组件

    并在您的组件中订阅您的功能:

    this.yourService.getMessage().subscribe(message => {
      this.data = message;
    });
    

    【讨论】:

      猜你喜欢
      • 2019-08-03
      • 2023-01-23
      • 2017-11-06
      • 2021-05-03
      • 2019-08-04
      • 1970-01-01
      • 2019-07-10
      • 2017-04-15
      • 1970-01-01
      相关资源
      最近更新 更多