简体   繁体   English

错误 TS2304:找不到名称“db”。 同时在 firebase 中推 object

[英]error TS2304: Cannot find name 'db'. while pushing object in firebase

I am trying to push an object using firebase, where angular will act as frontend.我正在尝试使用 firebase 推送 object,其中 angular 将充当前端。
component.html组件.html

<h3>Adding an object</h3>
<input type="text" (keyup.enter)="addCourse(course)" #course>

component.ts组件.ts

import { Component, OnDestroy } from '@angular/core';
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
import { Observable, of, Subscription } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  title = 'FirebaseDemo';
  // courses: any[];

  courses$;
  course$;
  author$;
  todos$: AngularFireList<any>;
  // subscription : Subscription;

  constructor(db: AngularFireDatabase) {
    // code to read the courses.
    db.list('/course')
      .valueChanges()
      .subscribe((inp) => {
        this.courses$ = inp;
        console.log(this.courses$);
      });
  }
  addCourse(value: string) {
    db.list('/course/').set('4', value);
  }
}

Here the last instance of db in addCourse(value) function is throwing error called cannot find name db.这里 addCourse(value) function 中的最后一个 db 实例抛出错误,称为找不到名称 db。
How can I access db variable out of constructor or How can I push the object in firebase?如何从构造函数中访问 db 变量或如何在 firebase 中推送 object?

Out of constructor, you can access db by using this.db.在构造函数之外,您可以使用 this.db 访问 db。 Please try the below change in you addCourse function and verify..请在您的 addCourse function 中尝试以下更改并验证..

addCourse(value: string) {
this.db.list('/course/').set('4', value);}

Also make changes to constructor to make db public/private like:还对构造函数进行更改以使数据库公共/私有,如:

constructor(public db: AngularFireDatabase) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM