我正在尝试以 Angular 复制一个属性(志愿服务到 x),因为我想编辑该属性并按原样保留志愿服务。这是来自 ts 的代码:
volunteership;
x ;
constructor(private viewvolunteershipService: Volunteership,
private router: Router) {}
ngOnInit() {
this.viewvolunteershipService.getVolunteership().subscribe(volunteership =>
this.volunteership = volunteership);
console.log("Volunteership", this.volunteership);
this.x = this.volunteership;
}
在这里,在 HTML 中,我想调用 ngFor 上的属性 x,这样我就可以从中选择一个城市,但它什么也没显示。如果我使用 volunteership 而不是 x 它工作得很好。如何将志愿服务复制到 x 以便从中选择一个城市?
<div class="form-group" >
<label for="city" >City</label>
<select id="city" class="form-group" >
<option value=""></option>
<option *ngFor=" let z of x" >{{z.city}}</option>
</select>
</div>
我已经尝试过复制为数组
for (var i = 0, len = this.volunteership.length; i < len; i++) {
this.x[i] = this.volunteerhip[i];
}
我什至尝试过使用 Object.assign() 方法,但仍然一无所获。
最佳答案
首先,您需要按照此处的说明在回调 (subscribe
) 中进行分配:How do I return the response from an Observable/http/async call in angular2?但是您提到您只希望更改反射(reflect)在 x
数组中。实际上,所有更改都将发生在两个数组上,因为 x
引用了 volunteership
,您可能想使用 Object.assign
:
ngOnInit() {
this.viewvolunteershipService.getVolunteership().subscribe(volunteership => {
this.volunteership = volunteership;
this.x = this.volunteership.map(obj => Object.assign({}, obj))
});
}
现在 x
数组将没有对 volunteership
数组的引用。
关于angular - 如何将 Angular 属性复制到另一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45171275/