IONIC 4:无法读取未定义的属性'get'

3

我正在尝试通过get()函数从数据库获取一些信息,但当我尝试运行时会出现标题中的错误。

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

我已经尝试使用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)

错误


发布您的服务代码 - Sajeetharan
1
问题不在于您的模板,而是在于您的TypeScript代码。看一下这行代码 this.adService.getAdAllList().get().then(.. 它看起来像是 getAdAllList() 返回了 null,因此在未定义的值上调用 get 会抛出错误。 - Kalenda
我发布了服务代码。 你说的有道理。使用这个代码,我放在 service.ts 中,我正在尝试请求的路径是错误的吗?我需要传递任何参数吗? - Caio Costa
你的问题在于你在准备好之前就试图访问它。我已经几周没有使用Firebase了,很快就会忘记一切,但我可以看出你缺少的核心概念是你正在处理异步数据流。我的建议是 - Firebase很难,找到一个好的Firebase教程,回到基础知识,否则即使提供了解决方案,你也不会真正理解它的作用。我是以友好的方式说这些话的。 - rtpHarry
1个回答

2
好的,你的代码中有一个情况没有被处理。如果在firebase.auth().onAuthStateChangeduser未定义,那么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 }
  ]


1
完美地工作了。我已经拿了一个与Firebase一起工作的例子,但我没有意识到每次打开应用程序时都需要检查用户是否已登录。谢谢。 - Caio Costa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接