Angular 入门 - windows.alert 不起作用

我正在使用 stackblitz 处理 angular 文档,并且到目前为止它让我创建的两个 window.alert 都不起作用。第一个是“共享”按钮,实际上只是我将它添加到 HTML 中,但是当我单击共享按钮时警报不起作用。有关故障排除的任何提示?

这是组件:

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

import { products } from '../products';

@Component({
  selector: 'app-product-list',templateUrl: './product-list.component.html',styleUrls: ['./product-list.component.css']
})
export class ProductListComponent {
  products = products;

  share() {
    window.alert('The product has been shared!');
  }

  onNotify() {
    window.alert('You will be notified when the product goes on sale');
  }
}

这是html:

    <h2>Products</h2>
    
    <div *ngFor="let product of products">
      <h3>
        <a [title]="product.name + ' details'">
          {{ product.name }}
        </a>
      </h3>
    
      <p *ngIf="product.description">
        Description: {{ product.description }}
      </p>
    
      <button (click)="share()">
        Share
      </button>
    
      <app-product-alerts [product]="product" (notify)="onNotify()">
      </app-product-alerts>
    </div>
linshi0 回答:Angular 入门 - windows.alert 不起作用

更新答案

问题似乎在于 stackblitz 如何将其代码/UI 组织到各种框架中,这似乎与 Chrome 的安全策略相冲突。当我在评论中单击 Robert 提供的 stackblitz 中的按钮时,没有警告对话框,我在控制台中看到以下警告:

一个不同的源子框架试图创建一个 JavaScript 对话框。这不再被允许并被阻止。有关详情,请参阅 https://www.chromestatus.com/feature/5148698084376576

尝试使用其他浏览器(例如 Edge),您应该会看到它可以正常工作。话虽如此,我建议在本地开发和运行(我最初的回答假设您正在这样做),以避免在 stackblitz 中工作时可能出现的任何其他“问题”。请参阅下面我的原始答案,使其在您的机器上编译/运行。

原答案

我怀疑您的应用程序没有编译(因此没有生成您添加的“警报”代码),因为我必须执行以下操作才能编译您的存储库:
  1. tsconfig.json复制到tsconfig.app.json
  2. npm i -D @angular/cli@12.0.5 @angular/compiler-cli@12.0.5 typescript@4.2

一旦我这样做并运行 npm start,警报就起作用了。

,

你是否只尝试过 alert() 方法,尽管 window.alert() 也应该可以工作。 typescript 库也为我们提供了一个 alert() 方法。 此外,如果您可以提供指向您的代码片段的 stackblitz 链接,我们可以让您了解更多有关您的代码无法正常工作的信息。

同时,下面是显示 window.alert() 和 alert() 都在 angular 中工作的链接。

https://stackblitz.com/edit/angular-ivy-byyhco

本文链接:https://www.f2er.com/1243.html

大家都在问