【问题标题】:Trying to access doc info using object properties尝试使用对象属性访问文档信息
【发布时间】:2019-10-03 06:12:42
【问题描述】:

潜伏已久,第一次发问。

我正在尝试学习 Angular 7,并且正在制作一个用于将大学橄榄球队添加到数据库并检索数据的 crud 应用程序。我正在使用 google firestore 作为数据库。

我能够检索团队的 id 并将其存储在变量中,但我遇到了使用 id 检索文档,然后使用对象属性获取信息的问题。非常感谢任何帮助。

firebase.service.ts

import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Observable } from 'rxjs';   
import { Team } from '../team.model';

@Injectable({
  providedIn: 'root'
})
export class FirebaseService {

  constructor(public db: AngularFirestore) {
  }

  getTeam(id:string) {
    return this.db.doc('teams/' + id);
  }
}

team-home.component.ts

import { Component, OnInit } from '@angular/core';
import { FirebaseService } from '../../shared/firebase.service';
import { ActivatedRoute, Router } from "@angular/router";
import { Team } from '../team.model';

@Component({
  selector: 'app-team-home',
  templateUrl: './team-home.component.html',
  styleUrls: ['./team-home.component.css']
})
export class TeamHomeComponent implements OnInit {

  constructor(
   private router: Router,
    private firebaseService: FirebaseService,
    private actRoute: ActivatedRoute
  ) { }

  id = this.actRoute.snapshot.paramMap.get('id');
  team = this.firebaseService.getTeam(this.id);

  ngOnInit() {

  }

}

team-home.component.html

<p>
  {{team.schoolName}}
</p>
<router-outlet></router-outlet>

team.model.ts

export class Team {
    id: string;
    schoolName: string;
    teamName: string;
    location: string;
    conference: string;
}

当我运行应用程序并转到显示模板的页面时,除了来自 app.component 的标题外,什么都没有显示。再次,非常感谢任何帮助。

【问题讨论】:

    标签: angular google-cloud-firestore angular7


    【解决方案1】:

    您需要将获取数据的部分代码放在构造函数中或 ngOnInit()m 上,否则代码永远不会被执行

    constructor(
        private router: Router,
        private firebaseService: FirebaseService,
        private actRoute: ActivatedRoute
      ) { 
      id = this.actRoute.snapshot.paramMap.get('id');
      team = this.firebaseService.getTeam(this.id);
    }
    

    【讨论】:

    • 感谢您的回复。当我尝试这个时,我收到以下错误:ERROR in src/app/teams/team-home/team-home.component.ts(25,5): error TS2304: Cannot find name 'id'. src/app/teams/team-home/team-home.component.ts(26,5): error TS2304: Cannot find name 'team'. src/app/teams/team-home/team-home.component.ts(26,46): error TS2339: Property 'id' does not exist on type 'TeamHomeComponent'.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多