我有一个模态绑定的问题(父对子)我有一个数组,我从一个Web服务填充。然后将Array传递给modal。第一次调用时数组为空,但后续调用时没有,单击时我每次都得到[n-1]索引值而不是[n]索引值。这可能是什么原因?
子组件
汽车detail.html
<div class="modal-body">
<input [(ngModel)]="car.Id" type="number">
<input [(ngModel)]="car.make" type="string">
</div>
汽车细节component.ts
export class CarDetailComponent implements OnInit {
@Input() public car;
constructor(private appService: AppService,
public activeModal: NgbActiveModal,
private route: ActivatedRoute,private location: Location) { }
ngOnInit() {
}
父组件
汽车component.html
<label *ngFor="let car of carslist" (click)= "getCarDetailsById(car.id);open()">
{{car.make}}
<br/>
</label>
我得到id并将其传递给Web服务调用,然后打开模态。
**car.component.ts**
carDetailsList:any = [];
public getCarDetailsById(id:number):Car[]{
this.appService.getCarDetailsById(id).subscribe(
car =>{
this.carDetailsList=car;
for (let i = 0; i < this.carDetailsList.length; i++) {
console.log(car.make);
}
}
);
return this.carDetailsList;
}
在第一次调用时,数组为空,而不是后续调用。每次模态打开时,我都会获得之前的车辆详细信息。谢谢您的帮助。
您在服务返回值之前打开模式。您应该在subscribe
方法中打开模型。这就是为什么你没有第一次获得价值,在随后的通话中你总是得到旧价值。从父html模板中删除open()
。
public getCarDetailsById(id:number):Car[]{
this.appService.getCarDetailsById(id).subscribe( car =>{
this.carDetailsList=car;
for (let i = 0; i < this.carDetailsList.length; i++) {
console.log(car.make);
}
this.open();
return this.carDetailsList;
});
}
您的问题实际上是您执行异步方法(订阅只在服务器返回所请求的数据时执行)同步执行的函数,这样您的函数将在订阅执行到达之前结束并达到返回,这就是为什么当您的模态将弹出数组在第一次调用时将为空。
public getCarDetailsById(id:number):Car[]{
this.appService.getCarDetailsById(id).subscribe(
// 1 when the server return data the code here is executed
car =>{
this.carDetailsList=car;
for (let i = 0; i < this.carDetailsList.length; i++) {
console.log(car.make);
}
}
);
// until server return data the execution continue so the return statement is reached before the code after point 1 is executed
// the variable returned will be null in that case.
return this.carDetailsList;
}
尝试改为:
async getCarDetailsById(id:number):Promise<Car[]> {
var asyncResult = await this.appService.getCarDetailsById(id).toPromise();
console.log('this console.log will be executed once the async call is fetched and the value of the returned promise is stored in asyncResult');
return asyncResult;
}
然后在.then函数中返回的promise中将返回值绑定到Car []类型的值之一。
并且在打开模态时调用'getCarsDetailsRecovered'函数。
关于angular:qazxsw poi中异步调用的有用链接。