angular 2 Property' push'类型' Observable'

时间:2018-06-13 15:54:29

标签: angular firebase observable

我遇到推送数据的问题

component.ts

import { Component, OnInit } from '@angular/core';


import { AngularFireDatabase } from 'angularfire2/database';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-content',
  templateUrl: './content.component.html',
  styleUrls: ['./content.component.css']
})

export class ContentComponent implements OnInit {

  courses$:Observable<any[]>;

  authors$:Observable<any[]>;

  constructor(db:AngularFireDatabase){
    this.courses$ = db.list('/courses').valueChanges();
    this.authors$ = db.object('/authors/1').valueChanges();

  }
  add(course:HTMLInputElement){
    this.courses$.push(course.value);
    course.value = '';
  }

  ngOnInit() {

  }

}

HTML 我把输入放到输入

<input type="text" (keyup.enter)="add()">
<ul>
  <li *ngFor="let item of courses$ | async">
    {{ item | json }}
  </li>
</ul>

错误

content.component.ts(25,19):Property&#39; push&#39;在类型&#39; Observable&#39;。

上不存在

2 个答案:

答案 0 :(得分:1)

由于observable不是数组,因此无法将新数据推送到它们。你想要这样的东西,你订阅数据库的变化。

  export class ContentComponent implements OnInit {

  courses:Array<any>;

  authors$:Observable<any[]>;

  constructor(db:AngularFireDatabase){
    db.list('/courses').valueChanges().subscribe(res => this.courses = res);
    this.authors$ = db.object('/authors/1').valueChanges();

  }
  add(course:HTMLInputElement){
    this.courses.push(course.value);
    course.value = '';
  }

  ngOnInit() {

  }

}

答案 1 :(得分:0)

import {Component} from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    courses$;
    courseObservable;
    authors$;
    constructor(db: AngularFireDatabase) {
        this.courseObservable = db.list('/courses');
        this.courses$ = this.courseObservable.valueChanges();
        this.authors$ = db.object('/authors/1').valueChanges();

    }
    add(course: HTMLInputElement) {
        this.courseObservable.push(course.value);
        course.value = '';
    }
}

HTML

<input type="text" (keyup.enter)="add()">
<ul>
  <li *ngFor="let item of courses$ | async">
    {{ item | json }}
  </li>
</ul>