【问题标题】:Document created but response is null文档已创建但响应为空
【发布时间】:2020-02-09 21:40:47
【问题描述】:

我的代码有两个问题。首先,即使日志告诉我刚刚创建的网站,我总是会收到错误消息:“已存在具有此名称的网站”。这可能是因为我的回答是空的。其次,我不知道如何将documentId 从createWebsite 返回到onConfirmButtonClick(),因此我可以将其用于进一步处理。有什么想法可以解决这个问题吗?

在组件中:

 onConfirmButtonClick() {
    this.websiteService.createWebsite(this.websiteName).then(result => {
      if(result) {
        this.toastrService.success('Your website has been created.');
        this.activeModal.close();
      } else {
        this.toastrService.error('A website with this name already exists.');
      }
    });
  }

在役:

  async createWebsite(name) {
    return this.afs.collection('websites', (ref) => ref.where('name', '==', name).limit(1)).get().subscribe(websites => {
      if(websites.size == 0) {
        const documentId = this.afs.createId();
        const documentPath = `websites/${ documentId }`;
        const documentRef: AngularFirestoreDocument<any> = this.afs.doc(documentPath);
        this.logger.debug(`Created a website at: '/${ documentPath }'`);
        return documentRef.set({name: name}, { merge: true });
      } else {
        this.logger.debug(`A website with the name '${name}' already exists`);
      }
    })
  }

【问题讨论】:

    标签: javascript angular firebase google-cloud-firestore


    【解决方案1】:

    在服务中执行以下操作:

    createWebsite(name) {
        return this.afs.collection('websites', (ref) => ref.where('name', '==', name).limit(1)).get();
      }
    

    这将返回一个 observable,然后在组件中订阅该 observable。:

    onConfirmButtonClick() {
        this.websiteService.createWebsite(this.websiteName).subscribe(websites => {
          if(websites.size == 0) {
            const documentId = this.afs.createId();
            const documentPath = `websites/${ documentId }`;
            const documentRef: AngularFirestoreDocument<any> = this.afs.doc(documentPath);
            this.logger.debug(`Created a website at: '/${ documentPath }'`);
            documentRef.set({name: name}, { merge: true });
            this.toastrService.success('Your website has been created.');
            this.activeModal.close()
          } else {
            this.logger.debug(`A website with the name '${name}' already exists`);
          }
       });
      }
    

    然后您将在组件内拥有documentId,我不确定result 是什么......整个代码中没有任何迹象表明您正在使用resolve 从Promise 返回任何内容

    【讨论】:

    • 我很高兴,太好了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多