我已经在Angular 6中创建了一个包含两个组件的单页应用程序。正在通过数据服务与网络服务器通信。一个组件列出所有项目,另一组件允许用户将一个项目添加到该列表。有趣的是,在删除列表组件中的一项之后,通过调用getItems可以刷新列表,而从create组件调用get MatTableDataSource属性则不会。任何观点都将不胜感激。谢谢。
列表组件:
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);
}
}
我从您的问题中了解到,您需要添加组件中的数据并将其显示为其他组件列表中的更新数据。为此,您可以使用rxjs i,e subject功能。
为您服务:DataService:声明主题:
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);
}
}
)));;
}
在列表组件中,添加以下代码:
subscription:Subscription
then in the constructor:
constructor(private data: DataService){
this.subscription=this.dataService.getNotification().subscribe(data=>{
if(data)
{
this.getItems();
}
});
}
它将正常工作,并且每次添加和删除时都会更新您的列表。
在组件销毁后始终取消订阅主题,以避免列表组件中出现不必要的内存泄漏。
ngOnDestroy():void
{
this.subscription.unsubscribe();
}