【发布时间】:2018-09-23 12:22:33
【问题描述】:
我在 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);
}
}
【问题讨论】:
-
你能提供你的
DataService类代码吗? -
嗨,比利,这里是:
标签: angular components interaction