如何通过服务将表单数据传递到另一个组件?

问题描述 投票:1回答:2

我在Angular 2(8)页面上有一个搜索表单,我想收集表单数据,将其提供给搜索服务,执行搜索/过滤(如果需要),然后将结果传递给渲染组件,因此将用户导航到另一个页面。

现在,在我的form.component.html中,我有:

<form #f="ngForm" (ngSubmit)="onSubmit(f)"
   fxLayout="column" fxLayoutAlign="start start">
   // some form fields
   <button 
     type="submit" 
     mat-raised-button 
     color="primary"
     [disabled]="f.invalid">Search</button>
</form>

因此,form.component.ts具有onSubmit方法:

onSubmit(form: NgForm) {
  const searchForm = form.value as SearchForm;
  console.log(searchForm);
}

这是我的问题开始的地方:我想将数据传递给searchService,也许像这样:

this.searchService.performSearch(searchForm)
  .subscribe(
    () => {
      router.navigate('/results');
    },
    () => { }
    );

然后我想在我的search.component.ts中访问此数据:

results = Result[];

并且在search.component.html中:

<app-search-item *ngFor="let result of results" [result]="result">
</app-search-item>

如何实现这种行为?

angular angular-services angular-components
2个回答
1
投票

您可以在导航的同时传递数据:

this.router.navigate('/results', { state: result });

您可以从路由器访问数据,如下所示:

this.router.getCurrentNavigation().extras.state

1
投票

从表单组件,您可以仅调用搜索服务的方法

this.serachService.search(input)

在搜索服务中,您可以具有结果数组并获取结果

results = Results[]
search(input){
// get results from your api here 
 this.http
        .get(`api/search/?name=${term}`).subscribe( res =>{
this.results = res;
 router.navigate('/results');

}

在搜索组件中,您可以使用this.searchService.results

© www.soinside.com 2019 - 2024. All rights reserved.