【发布时间】:2020-03-29 06:05:47
【问题描述】:
我正在尝试使用方法实现下拉,但它返回空。 如果我尝试放入 ngOninit 我会丢失我的快照路由器值并且无法返回 200 结果。 我把它放在构造函数里面,它返回值,但我又失去了我的值。
我得到了这样的结果(工作正常):
[{"hypervisorName":"Steve","hypervisorId":1},{"hypervisorName":"Docker","hypervisorId":2},
{"hypervisorName":"kubernetes","hypervisorId":3}]
我的后端方法:
[HttpGet("hyperforvm")]
public IActionResult GetHypervisorsForVm()
{
var model = from hyper in _context.Hypervisors
select new
{ HypervisorName = hyper.Name, HypervisorId = hyper.HypervisorId };
return Ok(model);
}
我的组件:
export class AddVmComponent implements OnInit {
model: any = {};
disabledProperty: boolean = true;
items: any;
constructor(private alertify: AlertifyService, private vm: VmService, private route:
ActivatedRoute, private http: HttpClient) {
this.items = this.getHyper()
}
ngOnInit() {
let projectId = +this.route.snapshot.paramMap.get('projectId')
this.model.projectId = projectId
this.model.managementId = 1
}
getHyper() {
this.vm.getHypervisorsForVm().subscribe(h => this.model = h)
}
}
我的 Html 看起来像:
<div class="input-group mt-1">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-dot-circle text-info"></i> Hypervisor
</div>
</div>
<select class="form-control" >
<option disabled>-Please choose hypervisor-</option>
<option *ngFor="let item of items" [value]="item.hypervisorId">
{{ item.hypervisorName }}
</option>
</select>
</div>
情况是我需要将 hypervisorId 保存到 db 并在下拉菜单中显示 hypervisorName (后端可以通过邮递员进行测试,一切正常)。问题无关紧要,我放入构造函数或 ngOninit 我丢失了我的快照值。内部构造函数 getHyper() 方法返回结果,但在 ngOninit 内部不返回。 但是这两种情况下的值都没有显示在下拉列表中。 如何显示 hypervisorName 保存 hypervisorId 并在它们旁边不丢失快照值。
【问题讨论】:
-
您应该对 items 而不是 Subscription 执行
ngFor。试试这样的:*ngFor="let item of model" -
你可以在构造函数中调用该方法:
this.vm.getHypervisorsForVm().subscribe(h => this.items = h) -
@shrys 感谢它帮助了我需要保存 hypervisorId 的一件小事,但在我的情况下,如果我使用简单的输入并手动添加整数,我在尝试保存时遇到异常 400,它可以正常工作,所以在这种情况下,我需要以某种方式从 getHyper() 中提取 hypervisorId 并保存此 id
标签: javascript c# angular typescript asp.net-core