gpt4 book ai didi

javascript - 从另一个组件调用组件函数 — 出现 "Cannot read property"错误

转载 作者:搜寻专家 更新时间:2023-10-30 21:26:24 25 4
gpt4 key购买 nike

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

警报组件

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)

最佳答案

您应该使用 @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();
}
}

附言:在调用 ngAfterViewInit 之前,您无法访问 QueueEditComponent 中的 AlertComponent。因此,请确保您的 saveQueuengAfterViewInit 之后的某个时间被调用。

关于javascript - 从另一个组件调用组件函数 — 出现 "Cannot read property"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54618423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com