Я создал одностраничное приложение в Angular 6 с двумя компонентами.Общаются с веб-сервером через сервис передачи данных.Один компонент перечисляет все элементы, другой компонент позволяет пользователю добавлять элементы в этот список.Интересно, что, вызывая getItems после удаления одного элемента в компоненте списка, он обновляет список, чего не вызывает вызов атрибута get MatTableDataSource из компонента create.Любые пункты очень ценятся.Благодарю.
Компонент списка:
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
});
});
}
}
Служба данных:
@Injectable({
providedIn: 'root'
})
export class DataService {
API_URL: string = 'https://cookie-munchies.herokuapp.com/api/items';
constructor(private http : HttpClient) { }
getItems(){
return this.http.get(this.API_URL);
}
postItem(name){
let item = {
name: name,
};
return this.http.post(this.API_URL, item);
}
deleteItem(id) {
return this.http.delete(`${this.API_URL}/${id}`);
}
updateItem(id, item: Item) {
// TODO: write update function
return this.http.put(`${this.API_URL}/${id}`, item);
}
}