订阅神秘不会触发

时间:2017-12-03 22:53:54

标签: angular observable angularfire2 google-cloud-firestore

所以我使用Angular和Firestore。出于某种原因,我可以在一个地方订购可观察到的罚款而不是另一个地方,我无法弄清楚原因。我觉得这可能是因为我曾经用它订阅了一次。我可以没有  运行订阅并同时使用take(1)?我没有错误,只是停在那里。

private jobDoc: AngularFirestoreDocument<Job>;
job: Observable<Job>;


ngOnInit() {
  this.route.params.subscribe(jobId => {
    this.createJobPage().then(function(result){
      this.job.subscribe(job => {
        console.log('this works');
      });
    }.bind(this));
  });
}


// When I load the page we run this function
createJobPage() {
  return new Promise(function(resolve){
    this.getUser().then(user => {
      this.jobDoc = this.afs.doc(`accounts/${user['cid']}/jobs/jobId`);
      this.job = this.jobDoc.valueChanges();
      this.job.take(1).subscribe(job => {
        console.log('this works');
      });
      resolve();
    });
  }.bind(this));
}


// Clicking a button saves the info
saveNewJob() {
  this.getUser().then(function(user) {
    console.log('this works, and shows "this.job" is an observable', this.job);
    this.jobDoc.update({id: 1})   // If I add this line it all works
    this.job.take(1).subscribe(job => {
      console.log('this does not work'); // This doesn't work
    });
    console.log('This works');
  }.bind(this));
}

-------- UPDATE --------

我认为这是一个错误。这有效:

this.jobDoc.update({id: 1})
this.job.take(1).subscribe(job => {
  console.log('this works');
});

但是,如果我删除了jobDoc更新,那么它不起作用,如下所示:

this.job.take(1).subscribe(job => {
  console.log('this works');
});

所以看来如果我想订阅这个,我需要首先给jobDoc一点动作来唤醒它......有谁知道为什么?

4 个答案:

答案 0 :(得分:1)

也许尝试使用first()而不是take(1),1次发出1并取消订阅。

答案 1 :(得分:0)

要修复它,我只是重新设置['hello world','this is a post'],但我不知道为什么我需要这样做。也许是个bug?如果有人知道,LMK

this.job

答案 2 :(得分:0)

不是错误,this.jobthis.jobDoc

的引用

在进一步审核后saveNewJob()正在添加没有触发器的订阅者。

添加this.jobDoc.update是触发器:)

saveNewJob() {
  this.getUser().then(function(user) {
    console.log('this works, and shows "this.job" is an observable', this.job);
    this.jobDoc.update({id: 1})   // If I add this line it all works
    this.job.take(1).subscribe(job => {
      console.log('this does not work'); // This doesn't work
    });
    console.log('This works');
  }.bind(this));
}

答案 3 :(得分:0)

这让我很好奇所以我去了firebase源文档并找到了这个https://github.com/angular/angularfire2/blob/master/src/firestore/observable/fromRef.ts

valueChanges是从这些函数构建的,关键部分是:

export function fromRef<R>(ref: firebase.firestore.DocumentReference | 
    firebase.firestore.Query) {
    return _fromRef<typeof ref, R>(ref).share();
}

这是一个共享的可观察对象,因此一旦完成,它就会为所有当前和未来的订阅者完成。所以最初的take(1)完成了它,然后任何未来的订阅者都不会从中得到任何东西,这就是重新引用它的原因,因为它重新创建了共享的observable。