angular - ionic 4 : Cannot read property 'get' of undefined

标签 angular typescript ionic-framework ionic4

我试图通过 get() 函数从数据库中获取一些信息,但是当我尝试运行它时出现标题错误,指出

at HomeTabPage.push ../src/app/home-tab/home-tab.page.ts.HomeTabPage.ngOnInit (home-tab.page.ts: 18)

否 *ngFor 我已经尝试使用 Elvis 参数,但它没有用。我已经将我的主函数从 ngOnInit 中传递出来,并声明了另一个函数来引用,但它没有起作用。


home-tab.page.html


<ion-list >
    <ion-item *ngFor="let advert of advertList">
        <ion-thumbnail slot="start">
           <ion-img src="advert?.image"></ion-img>
         </ion-thumbnail>
         <ion-label>
           <h2 >{{advert?.name}}</h2>
           <h3 >{{advert?.price}}</h3>
           <p >{{advert?.description}}</p>
        </ion-label>
     </ion-item>
  </ion-list>

home-tab.page.ts


export class HomeTabPage implements OnInit {
  public advertList: Array<any>;

  constructor(private navCtrl: NavController, public adService: AdvertisingService) {}

  ngOnInit(){
    this.adService.getAdAllList().get().then(advertListSnapshot => {
      this.advertList = [];
      advertListSnapshot.forEach(snap =>{
        this.advertList.push({
          id: snap.id,
          name: snap.data().name,
          price: snap.data().price,
          description: snap.data().description,
          image: snap.data().picture
        });
      });
    });
  }
}

service.ts


export class AdvertisingService {
  public adAllListRef: firebase.firestore.CollectionReference;
  constructor() {
    firebase.auth().onAuthStateChanged(user => {
      if (user) {
        this.adAllListRef = firebase.firestore().collection(`/adverts/adAll/adList`);
      }
    });
  }

  //cRud -> Read
  getAdAllList(): firebase.firestore.CollectionReference {
    return this.adAllListRef;
  }
}

错误

HomeTabPage_Host.ngfactory.js? [sm]:1 ERROR TypeError: Cannot read property 'get' of undefined
    at HomeTabPage.push../src/app/home-tab/home-tab.page.ts.HomeTabPage.ngOnInit (home-tab.page.ts:18)
    at checkAndUpdateDirectiveInline (core.js:22099)
    at checkAndUpdateNodeInline (core.js:23363)
    at checkAndUpdateNode (core.js:23325)
    at debugCheckAndUpdateNode (core.js:23959)
    at debugCheckDirectivesFn (core.js:23919)
    at Object.eval [as updateDirectives] (HomeTabPage_Host.ngfactory.js? [sm]:1)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:23911)
    at checkAndUpdateView (core.js:23307)
    at callViewAction (core.js:23548)

ERROR

最佳答案

好的,有一种情况您的代码没有处理。如果 userfirebase.auth().onAuthStateChanged 中未定义怎么办?您的 this.adAllListRef 不会被初始化,因此在这种情况下您也会遇到同样的错误。

我可能无法提供工作代码,但我可以建议您处理此问题的方法:

由于此页面仅在user有效时才有效,所以尽量使用AuthGuard这可能是这样的:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, Route } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable()
export class AuthGuard implements CanActivate {


  constructor(private _router: Router,private _advSvc: AdvertisingService) {
  }

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> 
  {
    return new Promise((resolve) => {
      firebase.auth().onAuthStateChanged(user => {
         if (user) {
            resolve(true);
         }else{
           this._router.navigate(['/login']);
           resolve(false);
         }
      });
   }
}

AdvertisingService 中,您不需要检查 user,因为它只是因为 AuthGuard 验证了用户而被调用。

export class AdvertisingService {
  constructor() {
  }

  getAdAllList(): firebase.firestore.CollectionReference {
    return firebase.firestore().collection(`/adverts/adAll/adList`);
  }
}

并将router定义为:

  const route = [
    { .... },
    {path: '/home',component: HomeTabPage, canActivate: [AuthGuard] },
    {path: '/login',component: LoginPage }
  ]

关于angular - ionic 4 : Cannot read property 'get' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56822060/

相关文章:

angular - 使用 ts-node 部署 Heroku

javascript - 如何实现使用 Angular 6 创建的表格左侧的复选框?

typescript - 如何在 typescript 中使用静态方法扩展和键入导入的类

angular - 在 Ionic 4 中导入幻灯片时显示错误

javascript - JAWS 18 不支持 aria-modal

Angular - fxFlex 对元素没有影响

javascript - 如何使用 Angular(8) UI 在远程 Linux 服务器上运行 shell 脚本?

node.js - 在 TypeScript 中,如何将 Promises 与 Node.js 上的 RSVP 实现结合使用

javascript - 当我传递一个 ID 时,函数参数接收到一个空字符串

android - 在 linux 上找不到 ionic 路径