angular6材质事件发射器不起作用

时间:2018-09-05 18:04:57

标签: angular angular-material angular6 angular-event-emitter

我正在尝试实现事件发射器,以便在将待办事项插入数据库时​​将其添加到待办事项列表中。但这行不通。请在下面找到代码: todoinput组件(todo.input.html):向数据库添加待办事项的组件

import { Component, OnInit, EventEmitter, Output } from '@angular/core';
import { Todos } from '../../models/Todos';
import { TodosService } from '../../services/todos.service';

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

  @Output() newTodo: EventEmitter<Todos> = new EventEmitter();

  constructor(private _todosService: TodosService) { }

  ngOnInit() {

  }

  addTodo(text) {
    this._todosService.addTodo({
      text: text,
    }).subscribe((todo) => {
      this.newTodo.emit(todo);
    })
  }

}

app.component.html:包含所有组件。

<app-navbar></app-navbar>
<app-todoinput (newTodo)="onNewTodo($event)">
</app-todoinput>
<app-todolist>
</app-todolist>

todolist.component.ts:将todo添加到待办事项列表中

import { Component, OnInit } from '@angular/core';
import { Todos } from '../../models/Todos';
import { TodosService } from '../../services/todos.service';

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

  todos: Todos[]

  constructor(private _todosService: TodosService) {
  }

  ngOnInit() {
    this._todosService.getTodos().subscribe((todos) => {
      this.todos = todos;
    })
  }

  onNewTodo(todo: Todos) {
    console.log('-- the passed todo --', todo);
    this.todos.unshift(todo);
  }
}

当将待办事项添加到数据库时,它将尝试发出newTodo。但这会引发以下错误:

AppComponent.html:2 ERROR TypeError: _co.onNewTodo is not a function
    at Object.eval [as handleEvent] (AppComponent.html:2)
    at handleEvent (core.js:10258)
    at callWithDebugContext (core.js:11351)
    at Object.debugHandleEvent [as handleEvent] (core.js:11054)
    at dispatchEvent (core.js:7717)

看起来像是正确的实现。谁能让我知道我做错了什么?它不适用于事件发射器吗?

谢谢

1 个答案:

答案 0 :(得分:1)

根据您的示例,您已经在<app-todoinput (newTodo)="onNewTodo($event)">的HTML中定义了此模板AppComponent。而您的onNewTodo($event)todolist.component.ts的一部分。因此就是错误。

您应该做的是,由于您想在两个同级组件之间更改数据,因此您应该使用BehaviorSubject而不是子组件中的Output属性来实现服务。