Angular 6:将数据添加到另一个组件后,在其中一个组件中更新表

时间:2018-09-23 12:22:33

标签: angular components interaction

我已经在Angular 6中创建了一个包含两个组件的单页应用程序。正在通过数据服务与网络服务器通信。 一个组件列出所有项目,另一组件允许用户将一个项目添加到该列表。 有趣的是,在删除列表组件中的一项之后,通过调用getItems可以刷新列表,而从create组件调用get MatTableDataSource属性则不会。 任何观点都将不胜感激。谢谢。

列表组件:

HDC hdc = GetDC(HWND_DESKTOP);
BitBlt(hdc, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), hdc, NULL, NULL, NOTSRCCOPY);

创建组件:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { MatTableDataSource } from '@angular/material/table';

import { Item } from '../items.model';

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

  public items = new MatTableDataSource<Item>();
  private displayedColumns = ['name', 'status', 'actions'];

  constructor(private data: DataService) { }

  ngOnInit() {
    this.getItems();
    console.log('New list page initialized');
  }

  getItems() {
    this.data.getItems().subscribe( (items: Item[]) => {
      this.items.data = items;
      console.log(this.items);
    });
  }

  deleteItem(id) {
    this.data.deleteItem(id).subscribe( (res) => {
      console.log(res);
      this.getItems();
    });
  }
}

数据服务:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { ListComponent } from '../list/list.component';
import { Item } from '../items.model';

import { MatSnackBar } from '@angular/material';

import {FormGroup, FormBuilder, Validators } from '@angular/forms';


@Component({
  selector: 'app-create',
  providers: [ListComponent],
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {

  createForm: FormGroup;

  constructor(private list: ListComponent ,private data: DataService, private fb: FormBuilder, private snackBar: MatSnackBar) {
    this.createForm = this.fb.group( {
      name: ['', Validators.required],
      status: ['']
    });
   }

  ngOnInit() {
  }

  addItem(name) {
    this.data.postItem(name).subscribe( (res) => {
      console.log(res);
      this.data.getItems().subscribe( (item: Item[])  => {
        this.list.items.data = item;
      })
      this.snackBar.open('Your item was succesfully added to the shopping list.', 'Cool!', {
        duration: 3000
      });
    });
  }
}

1 个答案:

答案 0 :(得分:2)

我从您的问题中了解到,您需要添加组件中的数据并在其他组件列表中将其显示为已更新。 为此,您可以使用rxjs即主题的功能。

在您的DataService中:

//declare a subject instance

private subject =new Subject<any>();

//Value is any string message or boolean value
//this will notify that you have added or deleted the data successfully and you //want other component to listen that

sendNotification(value:any)
{
    this.subject.next({text:value});
}

//this will be subscribed by the listing component which needs to display the //added/deleted ie updated list.

getNotification(){
    return this.subject.asObservable();
}

//In the method which you are saving data either by http client or in a list. In //its success call sendNotification method.

postItem(name){
    let item = {
      name: name,
    };

    return this.http.post(this.API_URL, item).pipe(
      map((data=>{
        this.sendNotification(true);
        }
      }
    )));
  }
 deleteItem(id) {
    return this.http.delete(`${this.API_URL}/${id}`).pipe(
      map((data=>{
        this.sendNotification(true);
        }
      }
    )));;
  }

在您的列表组件中,添加以下代码:

// create a field of type Subscription
subscription:Subscription

//then add the following code in constructor:

constructor(private data: DataService){
this.subscription=this.dataService.getNotification().subscribe(data=>{
      if(data)
      {
        this.getItems();
      }
    });
}

它可以正常工作,并且每次添加和删除时都会更新您的列表。

在组件销毁后总是取消订阅主题,以避免列表组件中的不必要的内存泄漏

ngOnDestroy():void
  {
      this.subscription.unsubscribe();
  }