首页 > 解决方案 > 服务初始化一次但不是第二次

问题描述

我刚刚在我一直在玩的应用程序中发现了一个错误,这对我来说似乎没有意义。

问题:我在不同的 MatTab 上有两个组件。每个都正确实例化并在选项卡更改之间被破坏。我的 Post 服务正在返回一个 observable 并完美地填充我的数据表。所以就像一个愚蠢的孩子,我进入我的服务并尝试清理代码。从以下位置更改邮政服务后:

     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)
     });

标签: angularserviceobservablengoninitngondestroy

解决方案


根据您提供服务的位置,它会被实例化。这意味着,您可以通过在服务中使用它来拥有单例服务:

@Injectable(){
providedIn: 'root'
}

或者通过将其作为依赖项添加到单个模块的“提供者”数组中。

但是要在组件中使用它时每次都重新实例化它,您应该在组件级别提供它:

@Component({
 selector: 'your-component',
 template: `...`,
 providers: [ NonSingletonService]
})

推荐阅读