我对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。请检查我的代码的正确性,因为我不想学习糟糕的编程。谢谢。
可能在BsModalService:
中constructor(private modalService:BsModalService)
然后您可以通过以下方式使用:
const modal = this.modalService.show(ModalGeonameComponent);
(<ModalGeonameComponent>modal.content).onClose.subscribe(result => {
if(result) {
this.result = Object.assign({}, result);
.....
}
});
您可以使用Component Interaction实现。如果'ModalGeonameComponent'组件是'MapViewComponent'的子组件,则可以使用Output property。将数据从子组件传递给父组件。如果这两个组件处于同一级别(不是父组件-子组件),则可以创建共享它们之间的服务(使用Observable),并将数据从一个组件传递到另一个组件。