从另一个组件调用组件的功能 - 让“无法读取属性”错误

问题描述 投票:2回答:1

我试图通过传递一个组件的引用到另一个,但得到“无法读取属性”的错误来调用的部件的另一部分功能。下面是代码

Alert组件

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

}

Alert组件的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)
javascript angular typescript components
1个回答
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:你不会有机会获得AlertComponentQueueEditComponent直到ngAfterViewInit被调用。因此,请确保您的saveQueue得到ngAfterViewInit后的某个调用。

© www.soinside.com 2019 - 2024. All rights reserved.