我在角度4应用程序中使用@ ng-bootstrap。
我能够打开一个模态实例,并能够将数据传递给模态。 在模态关闭我能够从模态得到结果。
我面临的问题是我试图在使用模态的父组件内部分配一些现有变量。 但它显示以下错误。
错误错误:未捕获(在承诺中):TypeError:无法读取属性' push'未定义的 TypeError:无法读取属性' push'未定义的
以下是我写给模态
的代码import { Component, OnInit, Input } from '@angular/core';
import { AdminService } from "../admin.service";
import { NgbModal, ModalDismissReasons, NgbAlertConfig } from '@ng-bootstrap/ng-bootstrap';
import { NgAddModalComponent } from './add-modal.component';
@Component({
selector: 'app-name-list',
templateUrl: './name-list.component.html',
styleUrls: ['./name-list.component.css'],
providers: [NgbAlertConfig]
})
export class NameListComponent implements OnInit {
errorMessage: string;
name: string;
nameList: [];
constructor(private adminService: AdminService, private modalService: NgbModal) {}
ngOnInit() {
this.adminService.getNamelist()
.subscribe(res => {
this.nameList = res.name; //["john", "smith", "todd"]
},
error => this.errorMessage = <any>error);
}
onAddClick() {
const modalRef = this.modalService.open(NgAddModalComponent, {size: 'lg'});//To open Modal
modalRef.componentInstance.name = this.name;//To send data to Modal
modalRef.result.then((result) => {//To subscribe data from Modal
this.nameList.push(result.name); //Getting error on this line
});
}
}
任何帮助将不胜感激!!!
答案 0 :(得分:1)
你对名单的声明是错误的。
您需要声明如下:
nameList = [];
不是这样的:
nameList: [];
答案 1 :(得分:0)
在解决结果承诺时,您需要传递onReject函数
modalRef.result.then((result) => {
/* To subscribe data from Modal */
}, (reason)=>{
/*Leave empty or handle reject*/
});
答案 2 :(得分:0)
您可以按以下方式处理撤退:
Component.ts:
import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
....
constructor(
private modalService: NgbModal
) {}
modalRef: any;
closeResult: any;
openModal() {
this.modalRef = this.modalService.open(SampleModalComponent);
this.modalRef.result.then((result) => {
console.log(result);
},
(reason) => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
console.log(this.closeResult);
});
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}