【发布时间】:2019-11-19 08:40:55
【问题描述】:
我对 Angular 有另一个问题。我不知道如何从模态返回数据。一个对象列表显示在我的模式中,然后单击列表中的一个项目后,我将对象传递给函数。如何在另一个组件中接收这个对象?
modal-geoname.component.html
<ng-scrollbar #scrollable track="vertical" *ngIf="geonames.length > 0">
<table class="table table-hover mb-0">
<tbody>
<tr *ngFor="let geoname of geonames; let i = index" style="cursor: pointer;" (click)="selectGeoname(geoname)">
<th scope="row">{{ i+1 }}</th>
<td><span class="flag-icon flag-icon-{{ geoname.country | lowercase }} mr-2"></span>{{ geoname.country }}, {{ geoname.zipcode }} {{ geoname.place }}</td>
<td>{{ geoname.admin }}</td>
</tr>
</tbody>
</table>
</ng-scrollbar>
modal-geoname.component.ts
export class ModalGeonameComponent implements OnInit {
public geonames: Geoname[] = [];
public selectedItem: Subject<boolean>;
constructor(public bsModalRef: BsModalRef) {}
selectGeoname(geoname: Geoname) {
this.selectedItem.next(geoname);
}
ngOnInit() {
this.selectedItem = new Subject();
}
}
modal.service.ts
@Injectable({ providedIn: 'root' })
export class ModalService {
bsModalRef: BsModalRef;
constructor(private bsModalService: BsModalService) {}
// ... other open modal functions ...
showGeonameModal(geonames: Geoname[]) {
this.bsModalRef = this.bsModalService.show(ModalGeonameComponent, {
initialState: { geonames },
class: 'modal-dialog modal-dialog-centered modal-lg',
ignoreBackdropClick: true
}).content.selectedItem.subscribe(selectedItem => {
console.log(selectedItem);
// I want to push selectedItem to itemList array in map-view.component.ts
});
}
}
map-view.component.ts
export class MapViewComponent {
private searchCountry: string;
private searchText: string;
public itemList: Geoname[] = [];
constructor(private geonameService: GeonameService, private modalService: ModalService) {}
searchCity() {
this.geonameService.getCity(this.searchText, this.searchCountry).subscribe((geonames) => {
this.modalService.showGeonameModal(geonames);
this.searchText = '';
});
}
}
我想将 selectedItem 传递给 itemList。请检查我的代码的正确性,因为我不想学习糟糕的编程。谢谢。
【问题讨论】:
标签: angular typescript service modal-dialog