我刚刚在我玩过的应用中发现了一个bug,对我来说似乎没有意义。
问题:我在不同的MatTab上有两个组件。每个实例都正确地实例化,并且在制表符更改之间被破坏。我的Post服务返回一个可观察的数据,并且完美地填充了我的数据表。因此,像个笨孩子一样,我忙于服务并尝试清理一下代码。从以下位置更改邮政服务后:
constructor(private afs: AngularFirestore, private router:Router, ) {
this.postsCollection = afs.collection<Post>(config.collection_endpoint);
this.posts =
this.afs.collection('posts').snapshotChanges()
.pipe(map(actions => actions.map(this.documentToDomainObject)));
}
getPosts(){
return this.afs.collection('posts').snapshotChanges()
.pipe(map(actions => actions.map(this.documentToDomainObject)));
}
这很好,但是我重复我自己,所以我决定清理它-将其更改为:
constructor(private afs: AngularFirestore, private router:Router, ) {
this.postsCollection = afs.collection<Post>(config.collection_endpoint);
this.posts =
this.afs.collection('posts').snapshotChanges()
.pipe(map(actions => actions.map(this.documentToDomainObject)));}
getPosts(){
return this.posts;}
更改代码后,我只能得到其中一个实例。是否有发生这种情况的原因?对我来说,这是相同的代码,我知道这里有些我不理解的东西,但是我一生无法发现它是什么。我在这里没有看到服务实例化的方式吗?再次感谢。
这里是feed.component,以防您也需要它。抱歉,我似乎无法在此处正确地发布代码。
export class FeedComponent implements OnInit,
OnChanges, OnDestroy {
postData: Post[] = [];
subDepartmentSelections: string[] = []
filteredData: any[] = []
dataReady: boolean = false;
dataSource: MatTableDataSource<any> = new
MatTableDataSource;
displayedColumns: string[] = ['User', 'Title',
"Description", "Date Available", "Contact"]
posts = this.ps.getPosts();
currentDepartment: string = ""
constructor(private ps: PostService, public dialog:
MatDialog, public change: ChangeDetectorRef, public
ms: MessageService) {}
ngOnInit() {
this.refreshPosts()
console.log("this is refreshing and data ready = " + this.dataReady)
}
refreshPosts() {
this.posts.subscribe(posts => {
this.dataReady = false;
this.postData = posts.filter(post =>
post.uid != `${this.currentUser.uid}` &&
post.claimedBy != `${this.currentUser.uid}`);
this.dataSource = new
MatTableDataSource(this.postData)
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort
this.dataReady = true;
console.log("this is refreshing and data ready = " + this.dataReady)
});
取决于您在哪里提供服务,它会被实例化。这意味着,您可以通过在服务中使用此服务来获得单例服务:
@Injectable(){
providedIn: 'root'
}
或通过将其添加为对单个模块的“ providers”数组的依赖关系。
但是要使它在组件中每次使用时都重新实例化,您应该在组件级别上提供它:
@Component({
selector: 'your-component',
template: `...`,
providers: [ NonSingletonService]
})