Reputation: 593
I have a search form on my Angular 2(8) page and I want to gather form data, give it to search service, perform a search/filtering (if needs be) and then pass the results to the rendering somponent, thus navigating user to another page.
Now, in my form.component.html I have:
<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>
So, the form.component.ts has the onSubmit method:
onSubmit(form: NgForm) {
const searchForm = form.value as SearchForm;
console.log(searchForm);
}
And this is where my question begins: I want pass data to the searchService, maybe something like:
this.searchService.performSearch(searchForm)
.subscribe(
() => {
router.navigate('/results');
},
() => { }
);
Then I want to access this data in my search.component.ts:
results = Result[];
And in the search.component.html:
<app-search-item *ngFor="let result of results" [result]="result">
</app-search-item>
How can I implement such a behavior?
Upvotes: 1
Views: 2795
Reputation: 722
from forms component you can just call a method of search service
this.serachService.search(input)
In search service you can have a results array and get the results
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');
}
In search component you can use this.searchService.results
Upvotes: 1
Reputation: 421
You can pass the data while navigating like this:
this.router.navigate('/results', { state: result });
And you can access the data from the router like this:
this.router.getCurrentNavigation().extras.state
Upvotes: 1