How to do page re-load with angular according to queryparms

Asked

Viewed 120 times

1

I have a simple input that serves as a search component, with the Submit function

onSubmit() {
    this.submitted = true;
    if (!this.searchForm.valid) {
      this.submitted = false;

    } else {
      this.router.navigate(['searchResult/'], {queryParams: {searchText: this.searchForm.get('searchText').value}});
    }
  }

After this, it goes to the results page, which presents the correct results. But on this page I have the same component, which when doing the search again, changes the value of my URL. However, the search is not performed again.

I believe ngOnInit has already been started, and I would need another way to do "ngOnInit Reload" how to do that? I did some research on Ngonchange but I believe it’s not what I need at the moment.

 ngOnInit() {
    this.searchTextResult = this.route.snapshot.queryParamMap.get('searchText');
    this.getHerosResultByName();
  }

2 answers

1

The ngOnChanges is triggered when a value of @Input() changes within the component do not trigger this event. You can test another alternative, rather than trigger the route. Use a BehaviorSubject to trigger the filter, in ngOnInit, you only subscribe to observable of the same:

private searchText = new BehaviorSubject<string>('');
searchText$ = this.searchText.asObservable();

ngOnInit() {
  this.searchText$
    .pipe(
      shareReplay(),
    )
    .subscribe((text) => {
      if ( text !== '' ) {
        this.searchTextResult = text
        this..getHerosResultByName();
      }
    })
}

onSubmit() {
  this.submitted = true;
  if (this.searchForm.valid) {
    this.searchText.next(this.searchForm.get('searchText').value)
  }
}

The way above, every time the value of the observable change the filter will be applied. No Reload.

  • It didn’t work my case. I think because ngOnInit is only fired once. But I wasn’t aware of Subject behavior, I’ll give a study

1


I decided to put a subscribe on my constructor

  constructor(
    private route: ActivatedRoute,
  ) {
    this.route.queryParamMap.subscribe((params) => {
      this.searchTextResult = params.get('searchText');
      this.getHerosResultByName();
    });
  }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.