Alertify 未在 Angular 中定义问题:12.0.4

问题描述

我尝试通过一些在线课程学习 Angular。当我尝试使用 Alertify 时,我收到一条错误消息:“在 ProductComponent.addToCart 中未定义 alertify”。我在下面分享相关代码

angular.json(我试图将路径更改为“../node_modules..”,所以开始双点但没有修复它。)

 "styles": [
              "src/styles.css","./node_modules/alertifyjs/build/css/alertify.min.css","./node_modules/alertifyjs/build/css/themes/bootstrap.min.css"
            ],"scripts": [
              "./node_modules/alertifyjs/build/alertify.min.js"
            ]

也试过用styles.css文件导入;

@import "~alertifyjs\build\css\alertify.min.css";
@import "~alertifyjs\build\css\themes\bootstrap.min.css"

component.ts;

import { Product } from './product';
declare let alertify: any;
@Component({
  selector: 'app-product',templateUrl: './product.component.html',styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {

  constructor() { }
  title ="Ürün Listesi";
  filterText="";
  products : Product[] = [
    {id:1,name:"Laptop",price:2500,categoryId:1,description:"Asus ZenBook",imageUrl:"https://images.unsplash.com/photo-1588702547923-7093a6c3ba33?ixid=MnwxMjA3fdb8MHxwaG90by1wYWdlfHx8fGVufdb8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80"},{id:2,name:"Mouse",price:300,categoryId:2,description:"Logitech G502",imageUrl:"https://images.unsplash.com/photo-1588440241012-ffd0331a05a8?ixid=MnwxMjA3fdb8MHxzZWFyY2h8MXx8ZzUwMnxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"},{id:3,name:"Klavye",price:1100,description:"Razer Kraken Klavye",imageUrl:"https://images.unsplash.com/photo-1563191911-e65f8655ebf9?ixid=MnwxMjA3fdb8MHxwaG90by1wYWdlfHx8fGVufdb8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80"},{id:1,{id:5,];

  ngOnInit(): void {
  };
  
  addToCart(product:any){
    
    alertify.success('Başarıyla eklendi.');
  


component.html;

  <a (click)="addToCart(product)" class="btn btn-primary action"
        >Sepete ekle</a
      >

这个 AddCart 函数在不使用 alertify 的情况下正常工作(例如简单的 alert("Added") 工作正常)。

我检查了 Alertifyjs 所在的路径,所有必需的文件都在那里。

解决方法

当你向 Angular 添加新库时,这个文件应该有脚本数组

"scripts": [
  "node_modules/alertifyjs/build/alertify.min.js"
],

另外应该是样式数组

"styles": [
  "src/styles.css"
  "node_modules/alertifyjs/build/css/alertify.min.css","node_modules/alertifyjs/build/css/themes/bootstrap.min.css"
],

之后就可以如下导入

import * as alertify from 'alertify';

有关更多信息,您可以查看官方 Angular 文档