【问题标题】:_co.addCourse() is not a function- even though I have defined it in the ts file_co.addCourse() 不是一个函数——即使我已经在 ts 文件中定义了它
【发布时间】:2019-01-12 06:49:54
【问题描述】:

所以我对 Ionic-angular 开发非常陌生,现在我只是想在我的 home.ts 文件中定义一个函数,并在我的 home.html 文件中调用它,以便在我的 FirebaseDB 中进行基本的创建.这是我的 home.html 文件:

home.html
    <ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Blank
    </ion-title>
    <ion-buttons end>
        <button ion-button icon-only (click)="addCourse()">
          <ion-icon name="add"></ion-icon>
        </button>
      </ion-buttons>
  </ion-navbar>

</ion-header>

<ion-content padding>
</ion-content>

这是我的 home.ts 文件

home.ts
    import { Component } from '@angular/core';
import { NavController, AlertController } from 'ionic-angular';
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
import { Observable } from '../../../node_modules/rxjs';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  songsList: AngularFireList<any>;
  songs: Observable<any>;

  constructor(public navCtrl: NavController, public afDB: AngularFireDatabase, public alertCtrl: AlertController) {
    this.songsList = this.afDB.list('/songs');
    this.songs = this.songsList.valueChanges();

    function addCourse(){
      let prompt = this.alertCtrl.create({
        title: 'Course Name',
        message: "Enter the Course Code",
        inputs: [
          {
            name: 'title',
            placeholder: 'Title'
          },
        ],
        buttons: [
          {
            text: 'Cancel',
            handler: data => {
              console.log('Cancelled');
            }
          },
          {
            text: 'Save',
            handler: data => {
              const newSongRef = this.songs.push({});

              newSongRef.set({
                id: newSongRef.key,
                title: data.title
              });
            }
          }
        ]
      });
      prompt.present();
    }
  }


    }

当我从 function addCourse(){...} 中删除声明“函数”时出现错误,但我在网站上收到此错误

_co.addCourse() is not a function. (In '_co.addCourse()','_co.addCourse() is undefined)

首先我认为这是因为我应该在构造函数之外定义函数,但是我如何调用数据库或警报控制器?

感谢您的帮助!

【问题讨论】:

  • 你在构造函数中定义了它,而不是在类中

标签: angular typescript ionic-framework


【解决方案1】:

你不应该有关键字function,它应该在构造函数之外,把它改成,

constructor(public navCtrl: NavController, public afDB: AngularFireDatabase, public alertCtrl: AlertController) {
}

addCourse(){
}

【讨论】:

  • 我会这样做吗 this.songsList = this.afDB.list('/songs');和 this.songs = this.songsList.valueChanges();也在构造函数之外?
  • 是的,在构造函数中
  • 当我在构造函数中移动它们时,我收到一个错误,即 Observable 类型上不存在 push 方法。我知道这是因为歌曲是一个 Observable,并且它连接到构造函数内的数据库,但是我该如何解决这个问题?
  • 你需要初始化songs数组songs:Observable = [];
  • 成功了!谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-25
  • 2017-04-30
  • 2022-12-12
  • 1970-01-01
  • 2021-01-29
  • 1970-01-01
相关资源
最近更新 更多