我有一个这样的页面:
父组件
第一个子组件:
第二个子组件
第三个子组件
我认为有两种方法:
使用Angular Observable在父组件中初始化表单时,哪种方法是在子组件中调用相同API的更好方法?
答案 0 :(得分:0)
对于不经常更改的数据(例如国家/地区列表),您的服务可以保留这组值。
像这样的东西(保留产品,但你可以为国家改变它):
@Injectable()
export class ProductService {
private productsUrl = 'api/products';
private products: IProduct[];
constructor(private http: HttpClient) { }
getProducts(): Observable<IProduct[]> {
if (this.products) {
return of(this.products);
}
return this.http.get<IProduct[]>(this.productsUrl)
.pipe(
tap(data => this.products = data),
catchError(this.handleError)
);
}
}
您可以在此处找到此示例的完整代码:
https://github.com/DeborahK/Angular-Communication
然后只检索一次数据,调用此方法的子组件获取已检索的数据。
另一种选择是在父组件中使用解析器。然后,解析器的数据将自动供孩子们使用。
@Injectable()
export class ProductResolver implements Resolve<IProduct[]> {
constructor(private productService: ProductService,
private router: Router) { }
resolve(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<IProduct[]> {
return this.productService.getProducts();
}
}
然后在子组件中:
ngOnInit(): void {
this.product = this.route.parent.snapshot.data['product'];
}
您可以在此处找到此完整的源代码: