angular 2类型"Observable"上不存在属性"push" [英] angular 2 Property 'push' does not exist on type 'Observable'

查看:168
本文介绍了angular 2类型"Observable"上不存在属性"push"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在推送数据方面有问题

I am having a problem with push data

component.ts

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 我输入以获取输入

html i put input to get the put the input

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

错误

content.component.ts(25,19):类型可观察"的属性"push"不存在.

content.component.ts (25,19): Property 'push' does not exist on type 'Observable'.

推荐答案

由于可观察对象不是数组,因此无法将新数据推送到它们.您需要这样的内容来订阅数据库更改.

Because observables are not arrays, you can't push new data to them. You want something like this where you subscribe to database changes.

  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() {

  }

}

这篇关于angular 2类型"Observable"上不存在属性"push"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆