ReferenceError:警报未定义[已解决]

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

当我尝试通过构造函数执行我的函数

showWelcomeMessage()
时, 我收到错误
ReferenceError: alert is not defined
。可能是什么问题?我在 VS Code 中使用 Angular 19。我还想在构造函数调用之后通过按钮调用来执行该函数,如下所示
<button class="btn btn-success" (click)="showWelcomeMessage()">Show Welcome Text</button>

@Component({
  selector: 'app-data-binding',
  imports: [],
  templateUrl: './data-binding.component.html',
  styleUrl: './data-binding.component.css'
})
export class DataBindingComponent {

  firstName: string = "Lulu";
  rollNo: number = 121;
  isActive: boolean = true;
  currentDate: Date = new Date();
  myPlaceholder: string = "Enter your name"
  divBlue: string = "bg-primary";

  constructor() {
    console.log(this.firstName)
    this.isActive = false;
    console.log(this.isActive)

    this.showWelcomeMessage() // <------- problem

  }

  showWelcomeMessage () {
    alert("Welcome")
  }

}

已解决:

import { Component, Inject } from '@angular/core';
import { PLATFORM_ID } from '@angular/core'; 
import { isPlatformBrowser } from '@angular/common'; 

@Component({
  selector: 'app-data-binding',
  imports: [],
  templateUrl: './data-binding.component.html',
  styleUrl: './data-binding.component.css'
})
export class DataBindingComponent {

  firstName: string = "Lulu";
  rollNo: number = 121;
  isActive: boolean = true;
  currentDate: Date = new Date();
  myPlaceholder: string = "Enter your name"
  divBlue: string = "bg-primary";
  isBrowser: boolean;

  constructor(@Inject(PLATFORM_ID) platformId: Object) { 
    if(this.isBrowser = isPlatformBrowser(platformId)) {
      this.showWelcomeMessage()
    } 
  } 

  showWelcomeMessage() {
      alert('Welcome');
    }
}

我还可以使用此解决方案通过按钮调用来执行函数

showWelcomeMessage()

angular typescript angular19
1个回答
1
投票

您的代码正在服务器上执行(启用了SSR)并且在服务器中

alert
browser
window
不存在。

我们可以使用

afterNextRender
仅在存在警报的浏览器上执行代码。

showWelcomeMessage () {
    afterNextRender(() => {
      alert("Welcome");
    });
}

对于按钮单击,您可以尝试

isPlatformBrowser
(仅在浏览器上运行)或在执行之前检查警报是否存在。

export class AppComponent  { 
  isBrowser: boolean; 
  
  constructor( @Inject(PLATFORM_ID) platformId: Object) { 
    this.isBrowser = isPlatformBrowser(platformId); 
    console.log(this.isBrowser) 
  } 

  buttonCallback() {
    if(alert) {
      alert('Welcome');
    }
  }

  buttonCallback2() {
    if(this.isBrowser) {
      alert('Welcome');
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.