ERROR TypeError: Cannot read property 'unread' of undefined

ERROR TypeError: Cannot read property 'unread' of undefined

首次加载页面时,我一直收到以下错误,但我可以退出它,一切都按预期运行。

ERROR TypeError: Cannot read property 'unread' 
of undefined
at listing-element.ts:34
at Array.forEach (<anonymous>)
at SafeSubscriber._next (listing-element.ts:33)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
at SafeSubscriber.next (Subscriber.js:185)
at Subscriber._next (Subscriber.js:125)
at Subscriber.next (Subscriber.js:89)
at MapSubscriber._next (map.js:83)
at MapSubscriber.Subscriber.next (Subscriber.js:89)
at MapSubscriber._next (map.js:83)

我目前正在使用 Angular 4.4.3、Ionic-Angular 3.9.2、AngularFire2 5.0.0。

当我 运行 下面的代码时,一切都按预期工作,但我似乎无法摆脱在 init 上弹出的 Cannot read property 'unread' 错误,无论我有多少 if 语句把有问题的代码包起来。就像我有薛定谔的 Observable;我同时获得了我期望的数据,但它返回时未定义。我意识到这是由于 Observables 的异步性质,但在我的团队将我们的数据库切换到 Google Firestore 并因此不得不升级 AngularFire 2 之前,我对此没有任何问题。

我们的管道和 HTML 也有类似的问题。对于我们的 HTML,通常将代码包裹在 <div *ngIf="thread"> 中是可行的,这样它只会在我们获得列表数据后出现。但是,将 TypeScript 包装在 if (threads.length > 0 && threads) 之类的内容中没有任何作用,因为数据仍在控制台记录预期的结果。

    //listing-element.ts
    this.userId = this.auth.getUser().uid;
    this.listingProvider.checkUnreadThreads(this.listing.id).subscribe(threads => {
          threads.forEach(thread => {
            if (thread[this.userId].unread) { // <-Line 34 is here
              this.unread = true;
            }
          })
        })

    //listing-provider
      checkUnreadThreads(listingId) {
        return this.afs.collection(`listings/${listingId}/threads`)
          .snapshotChanges()
          .map(actions => {
            return actions.map(action => {
              const id = action.payload.doc.id;
              const data = action.payload.doc.data();
              return { id, ...data }
            });
          })
      }

    //listing-element.html
    <notification-badge *ngIf="userId === listingUserId && page.activity === true && unread"></notification-badge>

这是我认为相关的所有信息,但如果有人需要更多信息,我非常乐意提供我力所能及的一切。

您可以按照下图尝试。

this.afAuth.authState.subscribe(
      (auth) => {
        if (auth != null) {
            this.listingProvider.checkUnreadThreads(this.listing.id).subscribe(threads 
               => {
              threads.forEach(thread => {
                if (thread[auth.uid].unread) { // <-Line 34 is here
                  this.unread = true;
                }
              })
            })
          })
        }
      });

在尝试访问 unthread 之前检查用户是否存在线程 属性。如果您仍然遇到该问题,请告诉我

if (thread[this.userId] && thread[this.userId].unread) { 
              this.unread = true;
            }

return { id, ...data } 将 id 和所有数据字段合并为一个。

现在你的thread看起来像这样

id:....,
unread:....,
fieldx:....,
fieldy:..... etc

试试这个代码

this.userId = this.auth.getUser().uid;
this.listingProvider.checkUnreadThreads(this.listing.id).subscribe(threads => {
      threads.forEach(thread => {
        if (thread.id == this.userId && thread.unread) { 
          this.unread = true;
        }
      })
    })