【发布时间】:2022-01-19 06:27:29
【问题描述】:
我创建了一个接口名称 Alert ,其中包含(类型、消息)变量都是字符串。我还创建了一个名为 Alerts 的常量,其中包含一个 Alert 接口数组。当我想使用一个名为“alerts”的变量来访问接口 Alert 时,我收到一个名为 TS2564 的运行时错误:属性“alerts”没有初始化程序,并且没有在构造函数中明确分配。我已经为我的 HTML 模板安装了 ng-bootstrap。下面是我的代码。
- contact-form.component.ts
import { Component, OnInit } from '@angular/core';
interface Alert {
type: string;
message: string;
}
const ALERTS: Alert[] = [{
type: 'success',
message: 'This is an success alert',
}, {
type: 'info',
message: 'This is an info alert',
}, {
type: 'warning',
message: 'This is a warning alert',
}, {
type: 'danger',
message: 'This is a danger alert',
}, {
type: 'primary',
message: 'This is a primary alert',
}, {
type: 'secondary',
message: 'This is a secondary alert',
}, {
type: 'light',
message: 'This is a light alert',
}, {
type: 'dark',
message: 'This is a dark alert',
}
];
@Component({
selector: 'app-contact-form',
templateUrl: './contact-form.component.html',
styleUrls: ['./contact-form.component.css']
})
export class ContactFormComponent {
alerts: Alert[];
constructor() {
this.reset();
}
close(alert: Alert) {
this.alerts.splice(this.alerts.indexOf(alert), 1);
}
reset() {
this.alerts = Array.from(ALERTS);
}
}
- contact-form.component.html
<p *ngFor="let alert of alerts">
<ngb-alert [type]="alert.type" (closed)="close(alert)">{{ alert.message }}</ngb-alert>
</p>
<p>
<button type="button" class="btn btn-primary" (click)="reset()">Reset</button>
- app.component.html
<app-contact-form></app-contact-form>
- app.module.ts
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ContactFormComponent } from './contact-form/contact-form.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
@NgModule({
declarations: [
AppComponent,
ContactFormComponent
],
imports: [
BrowserModule,
FormsModule,
NgbModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
- 这是我的错误
错误:src/app/contact-form/contact-form.component.ts:43:3 - 错误 TS2564:属性 'alerts' 没有初始化程序,也不是绝对的 在构造函数中赋值。
43 个警报:警报[];
我正在使用
- Angular CLI:13.0.4
- 节点:14.15.5
- 包管理器:npm 6.14.11
- 操作系统:win32 x64
【问题讨论】:
标签: angular typescript interface components ng-bootstrap