Angular 当我使用MatDialog时,ngOnInit只在第一次启动。为什么?
我从Firebase获得了一些数据,并将它们用于一个名为Categories的组件中,该组件在MatDialog的对话框中打开 当我第一次打开对话框时,我得到了我的数据并显示出来。但是当我关闭对话框并重新打开时,数据消失了 我用ngOnInit订阅数据 添加event.component.tsAngular 当我使用MatDialog时,ngOnInit只在第一次启动。为什么?,angular,typescript,angular-material,Angular,Typescript,Angular Material,我从Firebase获得了一些数据,并将它们用于一个名为Categories的组件中,该组件在MatDialog的对话框中打开 当我第一次打开对话框时,我得到了我的数据并显示出来。但是当我关闭对话框并重新打开时,数据消失了 我用ngOnInit订阅数据 添加event.component.ts 导出类AddEventComponent实现OnInit{ 构造函数(私有对话框:MatDialog){} openDialog(){ const dialogRef=this.dialog.open(C
导出类AddEventComponent实现OnInit{
构造函数(私有对话框:MatDialog){}
openDialog(){
const dialogRef=this.dialog.open(CategoriesComponent{
高度:“400px”,
宽度:“600px”,
});
dialogRef.afterClosed().subscribe(结果=>{
log(`Dialog result:${result}`);//Pizza!
});
}
}
类别.组件.ts
导出类分类组件实现OnInit{
类别:类别【】;;
构造函数(私有categoryService:categoryService){
}
恩戈尼尼特(){
this.categoryService.getCategories().subscribe(categories=>{
控制台日志(类别);
这个。类别=类别;
});
}
}
categories.component.html
全部删除
-
{{category.name}}:{{category.color}
无类别
不
对
是不是我做错了什么?我是否需要通过对话框传递数据(此解决方案似乎不干净…)
谢谢 以下是服务:
categoriesCollection: AngularFirestoreCollection<Category>;
categories: Observable<Category[]>;
constructor(public afs: AngularFirestore) {
this.categoriesCollection = this.afs.collection('categories', ref => ref.orderBy('name', 'asc'));
this.categories = this.categoriesCollection.snapshotChanges().pipe(map(changes => {
return changes.map(a => {
const data = a.payload.doc.data() as Category; // To get the id form Firestore
data.id = a.payload.doc.id;
return data;
});
}));
}
getCategories() {
return this.categories;
}
categoriesCollection:AngularFirestoreCollection;
类别:可观察;
建造商(公共afs:AngularFirestore){
this.categoriesCollection=this.afs.collection('categories',ref=>ref.orderBy('name','asc');
this.categories=this.categoriesCollection.snapshotChanges().pipe(映射(更改=>{
返回changes.map(a=>{
const data=a.payload.doc.data()作为类别;//从Firestore获取id
data.id=a.payload.doc.id;
返回数据;
});
}));
}
getCategories(){
返回此项。类别;
}
如果我在ngOnInit中使用console.log进行调试,它会一直启动。因此,这是订阅的问题。服务可能不是单例服务,所以只需将代码切换到
getCategories()
就可以了
getCategories() {
this.categoriesCollection = this.afs.collection('categories', ref =>
ref.orderBy('name', 'asc'));
return this.categoriesCollection.snapshotChanges().pipe(map(changes => {
return changes.map(a => {
const data = a.payload.doc.data() as Category; // To get the id form Firestore
data.id = a.payload.doc.id;
return data;
});
}));
}
似乎这不是ngOnInit()的问题。它可以工作,但订阅不起作用。一切正常,在订阅调试之前,请尝试ngOnInit方法中的
console.log('test')
。它应该记录两次。问题可能在服务中。您可以共享代码吗?我将代码放在下面。