从另一个组件调用组件函数—出现“无法读取属性”错误

时间:2019-02-10 16:19:54

标签: javascript angular typescript components

我正在尝试通过将一个组件的引用传递给另一个组件,但收到“无法读取属性”错误来从一个组件调用另一个组件函数。这是代码

警报组件

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

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

export class AlertComponent implements OnInit {  
  AlertMessage:string;

  constructor() {        
   }

  showSuccessAlert(){       
      this.AlertMessage =  "Data saved successfully.";
  }

  ngOnInit() {
  }

}

警报组件html

<p>{{AlertMessage}}</p>

我正在从另一个组件调用showSuccessAlert函数

组件

import { Component, OnInit, Input, HostListener } from '@angular/core';
import { QueueService } from 'src/services/queue.service';
import { ActivatedRoute } from "@angular/router";
import { NgForm } from '@angular/forms';
import { Queue } from 'src/models/queue';
import { error } from 'util';
import { AlertComponent } from '../alert/alert.component';

@Component({
  selector: 'queue-edit',
  templateUrl: './queue.edit.component.html'  
})
export class QueueEditComponent implements OnInit{
    @Input() alert:AlertComponent;

    queue = new Queue();    
    constructor(private api: QueueService, private route: ActivatedRoute){
        this.route.params.subscribe(params => this.params = params);

    } 
    title = "Edit Support Queue";

    ngOnInit() { 
    }

    @HostListener('saveQueue')
    saveQueue(queue){
        this.alert.showSuccessAlert(); 
    }
}

html

<app-alert></app-alert>

错误

ERROR TypeError: Cannot read property 'showSuccessAlert' of undefined
    at QueueEditComponent.push../src/app/queue/queue.edit.component.ts.QueueEditComponent.saveQueue (queue.edit.component.ts:44)
    at Object.eval [as handleEvent] (QueueEditComponent.html:25)
    at handleEvent (core.js:19545)
    at callWithDebugContext (core.js:20639)
    at Object.debugHandleEvent [as handleEvent] (core.js:20342)
    at dispatchEvent (core.js:16994)
    at core.js:17441
    at HTMLButtonElement.<anonymous> (platform-browser.js:993)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:14051)

1 个答案:

答案 0 :(得分:3)

您应该使用@ViewChild而不是@Input。像这样:

import { ..., ViewChild } from '@angular/core';
...
import { AlertComponent } from '../alert/alert.component';

@Component({...})
export class QueueEditComponent implements OnInit{
    @ViewChild(AlertComponent) alert:AlertComponent;

    ...

    @HostListener('saveQueue')
    saveQueue(queue){
        this.alert.showSuccessAlert(); 
    }
}

PS::只有在调用AlertComponent之前,您才能访问QueueEditComponent中的ngAfterViewInit。因此,请确保您的saveQueuengAfterViewInit之后的某个时间被呼叫。