Angular2和Services与同一页面上的组件共享表单数据

时间:2019-05-20 15:57:52

标签: angular angular-services

我细化了搜索字符串后,我道歉,我能够找到具有类似要求的问题并回答:Angular2 Update View After Form Submission

我正在研究和练习,要求我创建一个包含第1列中的3个输入和第2列中的HTML表的表单。

第2列的HTML表中填充了一个外部JSON数组。但我要完成的工作是将用户提交的数据追加到新表的当前表末尾。

我在页面上同时具有表单和表格组件,并且分别工作。

问题::在我的研究过程中,我遇到了“服务”选项,可以在没有子父关系的组件之间共享数据。这是实现此目标的最佳方法吗?

以下是我的组件文件:

task-table.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
  selector: 'app-task-table',
  templateUrl: './task-table.component.html',
  styleUrls: ['./task-table.component.css']
})
export class TaskTableComponent implements OnInit {

title = 'Existing Task';
  constructor (private httpService: HttpClient) { }
  arrTask: string [];

  ngOnInit () {
      //console.log("Before Parse");
    this.httpService.get('./assets/task-json.json').subscribe(
      data => {
        this.arrTask = data as string [];    // FILL THE ARRAY WITH DATA.
        //console.log(this.arrTask[1]);
      },
      (err: HttpErrorResponse) => {
        console.log (err.message);
      }
    );
  }
}

task-form.component.ts:

import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { TaskObject } from '../task-object';

@Component({
  selector: 'app-task-form',
  templateUrl: './task-form.component.html',
  styleUrls: ['./task-form.component.css']
})
export class TaskFormComponent{

  model = new TaskObject(0,'First Task', '05/20/19', 'Miguel Blanco');

  submitted = false;

  onSubmit() { this.submitted = true;} 

}

task-object.ts

export class TaskObject {

      constructor(
    public id: number,
    public taskName: string,
    public taskDate: string,
    public taskAssigned: string
  ) {  }

}

我不确定下一步是否有任何直接或建议的帮助。

1 个答案:

答案 0 :(得分:1)

使用服务是在没有父子关系的组件之间共享数据的唯一方法。

首先,创建一个以Subject作为属性的服务

export class MyTransferService {

  subject: Subject<any> = new Subject();

  transfer = (data: any) => {
    this.subject.next(data);
  }
}

providers的元数据的app.module数组中注册一个单例服务。

providers: [ 
  MyTransferService,'
  // other singleton services
]

要从组件发送数据,请将服务注入到发送组件中,并在需要时调用transfer方法。就这么简单。

在接收端还需要进行一些设置。首先,在接收组件中添加一个Subscription属性:

private transferSubscription: Subscription;

然后,在组件OnInit中,通过订阅从服务主题获得的可观察对象来实例化订阅:

const obs = this.transferService.subject.asObservable();
this.transferSubscription = obs.subscribe(next => {
  // handle transferred data
});

最后,您需要退订以防止内存泄漏。让接收组件实现OnDestroy并在Subscription属性上调用退订。

ngOnDestroy() {
  this.transferSubscription.unsubscribe();
}