【问题标题】:Angular Eventemitter is not working角事件发射器不工作
【发布时间】:2018-07-04 12:06:07
【问题描述】:

在Angular 5中,我有多个组件,例如一个是标题组件,另一个是设置组件,第三个是日历组件。

当我从设置向标题组件发出事件时,它可以工作,但是当我转到日历链接时,它会生成如下所示的错误

错误:StaticInjectorError(AppModule)[HeaderComponent -> TodoComponent]:StaticInjectorError(平台:核心)[HeaderComponent -> TodoComponent]:

此处的代码示例

Header.component.ts 文件

import { Component, OnInit } from '@angular/core';
import {TodoComponent} from '../todo/todo.component';
@Component({
  selector: 'header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})

export class HeaderComponent implements OnInit {

  constructor(public todo:TodoComponent) {

    this.todo.change_company_logo.subscribe(data=>{
      console.log(data);
    })
   }

  ngOnInit() {
  }

}

Todo.component.ts 文件

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

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

export class TodoComponent implements OnInit {
  @Output() change_company_logo: EventEmitter<any> = new EventEmitter<any>();
  constructor() {

   }

  ngOnInit() {
  }
  fire(){
    this.change_company_logo.emit("hi");
  }
}

kanban.component.ts file

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

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

export class KanbanComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

route.ts 文件

import { ModuleWithProviders } from "@angular/compiler/src/core";
import { RouterModule } from '@angular/router';
import { Routes, Params } from '@angular/router';
import {TodoComponent} from './todo/todo.component'
import {KanbanComponent} from './kanban/kanban.component';

const appRoutes:Routes = [
    {path:'',component:TodoComponent},
    {path:'kanban',component:KanbanComponent}
];
export const routing:ModuleWithProviders = RouterModule.forRoot(appRoutes);

第一次默认组件是 todo.component.ts 并且有一个按钮可以向标题组件触发事件,当转到看板链接时它会在此代码上方定义的控制台中给出错误。

请指教。

【问题讨论】:

  • 您在哪个组件中将“开火”功能绑定到“开火”按钮?
  • 您正在通过构造函数将一个组件注入另一个组件。您将 services 注入组件,而不是其他组件。将 change_company_logo 移动到服务中,然后注入。
  • 实际上,我想使用事件发射器将一个值从一个组件发送到另一个组件,并且它正在从 todo 组件到标题但单击看板链接时会出错。有示例代码吗?

标签: angular


【解决方案1】:

您正在尝试使用构造函数在另一个组件中注入一个组件,在 Angular 中,您可以注入一个注释为 @Injectable 的服务。组件通信请参考here

【讨论】:

    【解决方案2】:

    @Output() change_company_logo: EventEmitter = new EventEmitter();

    可以这样

    @Output() change_company_logo = new EventEmitter();

    还有这个:

    ngOnInit() {}
    fire(){ this.change_company_logo.emit("hi"); }
    

    ngOnInit() { this.fire(); }
    fire(){ this.change_company_logo.emit("hi"); }
    

    你忘了叫火,你定义了它但没有叫它

    【讨论】:

    • 其实这个fire函数会在按钮点击时调用。
    • 你能用这个来做一个堆栈闪电战吗?这样的可读性不太好
    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 2018-06-05
    • 2016-11-20
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    相关资源
    最近更新 更多