Skip to content

Commit 4d0f505

Browse files
committed
chore: allow syncing UI state to URL
1 parent 38e6f43 commit 4d0f505

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

src/app/search/deeplink.service.ts

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { FormGroup } from '@angular/forms';
33
import { QueryParams } from './deeplink.service';
44
import { Injectable } from '@angular/core';
55
import { ActivatedRoute, Router, Params } from '@angular/router';
6+
import { map } from 'rxjs/operators';
67

78
export interface QueryParams {
89
q: string;
@@ -12,7 +13,11 @@ export interface QueryParams {
1213
providedIn: 'root'
1314
})
1415
export class DeeplinkService {
15-
constructor(private router: Router, private route: ActivatedRoute, private search: AlgoliaService) {}
16+
constructor(
17+
private router: Router,
18+
private route: ActivatedRoute,
19+
private search: AlgoliaService
20+
) {}
1621

1722
/**
1823
* Register a given FormGroup instance with the current "q" queryParams Observbale. Every time the
@@ -22,19 +27,32 @@ export class DeeplinkService {
2227
registerFormGroup(form: FormGroup, controlName: string) {
2328
this.route.queryParams.subscribe((query: QueryParams) => {
2429
if (query.q) {
25-
form.setValue({
30+
form.patchValue({
2631
[controlName]: query.q
2732
});
2833
}
2934
});
3035
}
3136

37+
registerState(queryParam: string) {
38+
return this.route.queryParams.pipe(map(query => query[queryParam]));
39+
}
40+
3241
/**
3342
* This method is used to update the current URL queryParams.
3443
* It is used to keep both the URL and the formControl in sync.
3544
* @param queryParams A given Params object containing the queryParams to set.
3645
*/
3746
syncUrl(queryParams: Params) {
47+
if (!queryParams.t) {
48+
queryParams.t = this.route.snapshot.queryParams.t;
49+
} else {
50+
if (!queryParams.q) {
51+
queryParams.q = this.route.snapshot.queryParams.q;
52+
}
53+
}
54+
55+
console.log(queryParams);
3856
this.router.navigate([], {
3957
relativeTo: this.route,
4058
queryParams

0 commit comments

Comments
 (0)