在我组件的ngOnInit中,ComProductService将首先获取产品类别并处理类别的第三级,并将其存储到服务中的proCatThird中。然后在我的fillFormValues()方法中,我需要从ComProductService获取proCatThird值。但是,从proCatThird返回的值是不确定的。有什么适当的方法可以将价值从一个订户传递到另一个订户?
ComProductService.service.ts
export class ComProductService {
baseUrl = environment.apiUrl + 'comProducts/';
proCatThird: ProCatThird[];
constructor(private http: HttpClient,
private authService: AuthService,
private errorHandler: ErrorService) { }
getProductCategories(): Observable<ProCatFirst[]> {
return this.http
.get(this.baseUrl)
.pipe(
map((response: ProCatFirst[]) => {
if (response) {
this.proCatThird = [];
response.forEach((first) => {
first.proCatSeconds.forEach((second) => {
second.proCatThirds.forEach((third) => {
this.proCatThird.push(third);
});
});
});
return response;
}
})
);
}
component.ts
constructor(
private activatedRoute: ActivatedRoute,
private comProductService: ComProductService,
) { }
ngOnInit() {
this.comProductService.getProductCategories().subscribe((response) => {
this.proCatFirst = response;
});
this.fillFormValues();
}
fillFormValues() {
this.activatedRoute.data.subscribe(data => {
this.product = data['product'];
this.productForm.patchValue({
name: this.product.name,
category: this.product.category,
});
const catName = this.comProductService.proCatThird.find(pct => pct.id === this.product.category).name;
});
}
答案 0 :(得分:1)
当前代码存在的问题是,fillForm是在不等待服务器响应的情况下启动的,并且proCatThird
属性未填充所需的响应。
请在您的组件中执行此操作
constructor(
private activatedRoute: ActivatedRoute,
private comProductService: ComProductService,
) { }
ngOnInit() {
this.comProductService.getProductCategories().subscribe((response) => {
this.proCatFirst = response;
this.fillFormValues(); // fill form values when the data has been received from server
});
}
fillFormValues() {
this.activatedRoute.data.subscribe(data => {
this.product = data['product'];
this.productForm.patchValue({
name: this.product.name,
category: this.product.category,
});
const catName = this.comProductService.proCatThird.find(pct => pct.id === this.product.category).name;
});
}
ngOnInit() {
this.comProductService.getProductCategories()
.pipe(
mergeMap((response) => {
this.proCatFirst = response;
been received from server
return this.activatedRoute.data;
})
)
.subscribe(data => {
this.product = data['product'];
this.productForm.patchValue({
name: this.product.name,
category: this.product.category,
});
const catName = this.comProductService.proCatThird.find(pct => pct.id === this.product.category).name;
});
}
这样,您将只有一个订阅,该订阅会在页面加载(组件初始化)时触发;