服务初始化一次但不会第二次

时间:2020-01-02 19:23:53

标签: angular service observable ngoninit ngondestroy

我刚刚在我玩过的应用中发现了一个错误,这对我来说似乎毫无意义。

问题:我在不同的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)
     });

1 个答案:

答案 0 :(得分:0)

根据您在何处提供服务,将其实例化。这意味着,您可以通过在服务中使用以下服务来获得单例服务:

@Injectable(){
providedIn: 'root'
}

或通过将其添加为对单个模块的“ providers”数组的依赖项。

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

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