how can route an array as a parameter in angular? - javascript

I configured routing module as following:
const routes: Routes = [
{
path: "engineering/:branches",
component: BranchesTabsComponent
},
{
path: "humanities/:branches",
component: BranchesTabsComponent
},
];
and in the main-continer.component.ts:
titlesOfEngineeringTabs: string[] = ['E1','E2','E3'];
titlesOfHumanitiesTabs: string[] = ['H1','H2'];
constructor(private router: Router) {}
handleEnginTabs():void{
this.router.navigate(['/engineering', this.titlesOfEngineeringTabs]);
}
handleHumanTabs():void{
this.router.navigate(['/humanities', this.titlesOfHumanitiesTabs]);
}
and also main-continer.component.html contains:
<router-outlet></router-outlet>
and then in branches-tabs.component.ts have:
tabsLable: string[] = [''];
ngOnInit(): void {
this.route.params.subscribe(param => this.tabsLable = param["branches"]);
}
till here, it is obvious that we want to replace <router-outlet> with branches-tabs component in which deferent tab labels are shown Depending on selected menu...
but I get this error:
*core.mjs:6485 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'engineering;0=%DA%A9%D8%A7%D9%85%D9%BE%DB%8C%D9%88%D8%AA%D8%B1;1=%D8%B5%D9%86%D8%A7%DB%8C%D8%B9;2=%D9%85%D8%AA%D8%A7%D9%84%D9%88%D8%B1%DA%98%DB%8C'
Error: Cannot match any routes. URL Segment: 'engineering;0=%DA%A9%D8%A7%D9%85%D9%BE%DB%8C%D9%88%D8%AA%D8%B1;1=%D8%B5%D9%86%D8%A7%DB%8C%D8%B9;2=%D9%85%D8%AA%D8%A7%D9%84%D9%88%D8%B1%DA%98%DB%8C'*
how can pass a string array as parameter and fix above error?
best regards

Angular docs on navigate()
An array of URL fragments with which to construct the target URL. If
the path is static, can be the literal URL string. For a dynamic
path, pass an array of path segments, followed by the parameters for
each segment. The fragments are applied to the current URL or the
one provided in the relativeTo property of the options object, if
supplied.
If your intent is to have the url look like /engineering/E1/E2/E3 then you should apply the spread operator ... to the arrays and it would look like:
this.router.navigate(['/engineering', ...this.titlesOfEngineeringTabs]);

If you want to put the array in the url, it needs to be a string. So you can use JSON.stringify() and JSON.parse()
handleEnginTabs():void{
this.router.navigate(['/engineering', JSON.stringify(this.titlesOfEngineeringTabs)]);
}
ngOnInit(): void {
this.route.params.subscribe(param => this.tabsLable = JSON.parse(param["branches"]));
}
But queryParams is probably more appropriate.
handleEnginTabs(): void {
this.router.navigate(['/engineering'], {
queryParams: { branches: this.titlesOfEngineeringTabs },
});
}
ngOnInit(): void {
this.tabsLable = this.route.snapshot.queryParams['branches'];
}
and removing the parameter from the path
{
path: "engineering",
component: BranchesTabsComponent
},
Keep in mind the user can change the values of your array by editing the url. If that's something you don't want to happen, you'll have to use other means of passing the data.
This thread goes over some other ways of passing data to routes:
How do I pass data to Angular routed components?
However, a lot of them will not persist on refresh. So if you want that, you'll have to write to / read from localStorage as well.

Related

How to properly use context in tRPC?

Let's say I have a very basic API with two sets of endpoints. One set queries and mutates properties about a User, which requires a username parameter, and one set queries and mutates properties about a Post, which requires a post ID. (Let's ignore authentication for simplicity.) I don't currently see a good way to implement this in a DRY way.
What makes the most sense to me is to have a separate Context for each set of routes, like this:
// post.ts
export async function createContext(
opts?: trpcExpress.CreateExpressContextOptions
) {
// pass through post id, throw if not present
}
type Context = trpc.inferAsyncReturnType<typeof createContext>;
const router = trpc
.router()
.query("get", {
resolve(req) {
// get post from database
return post;
},
});
// similar thing in user.ts
// server.ts
const trpcRouter = trpc
.router()
.merge("post.", postRouter)
.merge("user.", userRouter);
app.use(
"/trpc",
trpcExpress.createExpressMiddleware({
router: trpcRouter,
createContext,
})
);
This complains about context, and I can't find anything in the tRPC docs about passing a separate context to each router when merging. Middleware doesn't seem to solve the problem either - while I can fetch the post/user in a middleware and pass it on, I don't see any way to require a certain type of input in a middleware. I would have to throw { input: z.string() } or { input: z.number() } on every query/mutation, which of course isn't ideal.
The docs and examples seem pretty lacking for this (presumably common) use case, so what's the best way forward here?
This functionality has been added in (unreleased as of writing) v10. https://trpc.io/docs/v10/procedures#multiple-input-parsers
const roomProcedure = t.procedure.input(
z.object({
roomId: z.string(),
}),
);
const appRouter = t.router({
sendMessage: roomProcedure
.input(
z.object({
text: z.string(),
}),
)
.mutation(({ input }) => {
// input: { roomId: string; text: string }
}),
});

Unable to fetch dynamic queryParams without reloading the page [duplicate]

I am trying to update (add, remove) queryParams from a component. In angularJS, it used to be possible thanks to :
$location.search('f', 'filters[]'); // setter
$location.search()['filters[]']; // getter
I have an app with a list that the user can filter, order, etc and I would like to set in the queryParams of the url all the filters activated so he can copy/paste the url or share it with someone else.
However, I don't want my page to be reloaded each time a filter is selected.
Is this doable with the new router?
You can navigate to the current route with new query params, which will not reload your page, but will update query params.
Something like (in the component):
import {ActivatedRoute, Router} from '#angular/router';
constructor(
private router: Router,
private activatedRoute: ActivatedRoute,
) { }
public myMethodChangingQueryParams() {
const queryParams: Params = { myParam: 'myNewValue' };
this.router.navigate(
[],
{
relativeTo: activatedRoute,
queryParams: queryParams,
queryParamsHandling: 'merge', // remove to replace all query params by provided
});
}
Note, that whereas it won't reload the page, it will push a new entry to the browser's history. If you want to replace it in the history instead of adding new value there, you could use { queryParams: queryParams, replaceUrl: true }.
EDIT:
As already pointed out in the comments, [] and the relativeTo property was missing in my original example, so it could have changed the route as well, not just query params. The proper this.router.navigate usage will be in this case:
this.router.navigate(
[],
{
relativeTo: this.activatedRoute,
queryParams: { myParam: 'myNewValue' },
queryParamsHandling: 'merge'
});
Setting the new parameter value to null will remove the param from the URL.
#Radosław Roszkowiak's answer is almost right except that relativeTo: this.route is required as below:
constructor(
private router: Router,
private route: ActivatedRoute,
) {}
changeQuery() {
this.router.navigate(['.'], { relativeTo: this.route, queryParams: { ... }});
}
In Angular 5 you can easily obtain and modify a copy of the urlTree by parsing the current url. This will include query params and fragments.
let urlTree = this.router.parseUrl(this.router.url);
urlTree.queryParams['newParamKey'] = 'newValue';
this.router.navigateByUrl(urlTree);
The "correct way" to modify a query parameter is probably with the
createUrlTree like below which creates a new UrlTree from the current while letting us modify it using NavigationExtras.
import { Router } from '#angular/router';
constructor(private router: Router) { }
appendAQueryParam() {
const urlTree = this.router.createUrlTree([], {
queryParams: { newParamKey: 'newValue' },
queryParamsHandling: "merge",
preserveFragment: true });
this.router.navigateByUrl(urlTree);
}
In order to remove a query parameter this way you can set it to undefined or null.
The answer with most vote partially worked for me. The browser url stayed the same but my routerLinkActive was not longer working after navigation.
My solution was to use lotation.go:
import { Component } from "#angular/core";
import { Location } from "#angular/common";
import { HttpParams } from "#angular/common/http";
export class whateverComponent {
constructor(private readonly location: Location, private readonly router: Router) {}
addQueryString() {
const params = new HttpParams();
params.append("param1", "value1");
params.append("param2", "value2");
this.location.go(this.router.url.split("?")[0], params.toString());
}
}
I used HttpParams to build the query string since I was already using it to send information with httpClient. but you can just build it yourself.
and the this._router.url.split("?")[0], is to remove all previous query string from current url.
Try
this.router.navigate([], {
queryParams: {
query: value
}
});
will work for same route navigation other than single quotes.
If you want to change query params without change the route. see below
example might help you:
current route is : /search
& Target route is(without reload page) : /search?query=love
submit(value: string) {
this.router.navigate( ['.'], { queryParams: { query: value } })
.then(_ => this.search(q));
}
search(keyword:any) {
//do some activity using }
please note : you can use this.router.navigate( ['search'] instead of this.router.navigate( ['.']
I ended up combining urlTree with location.go
const urlTree = this.router.createUrlTree([], {
relativeTo: this.route,
queryParams: {
newParam: myNewParam,
},
queryParamsHandling: 'merge',
});
this.location.go(urlTree.toString());
Not sure if toString can cause problems, but unfortunately location.go, seems to be string based.
Better yet - just HTML:
<a [routerLink]="[]" [queryParams]="{key: 'value'}">Your Query Params Link</a>
Note the empty array instead of just doing routerLink="" or [routerLink]="''"
First, we need to import the router module from angular router and declare its alias name
import { Router } from '#angular/router'; ---> import
class AbcComponent implements OnInit(){
constructor(
private router: Router ---> decalre alias name
) { }
}
1. You can change query params by using "router.navigate" function and pass the query parameters
this.router.navigate([], { queryParams: {_id: "abc", day: "1", name: "dfd"}
});
It will update query params in the current i.e activated route
The below will redirect to abc page with _id, day
and name as query params
this.router.navigate(['/abc'], { queryParams: {_id: "abc", day: "1", name:
"dfd"}
});
It will update query params in the "abc" route along with three query paramters
For fetching query params:-
import { ActivatedRoute } from '#angular/router'; //import activated routed
export class ABC implements OnInit {
constructor(
private route: ActivatedRoute //declare its alias name
) {}
ngOnInit(){
console.log(this.route.snapshot.queryParamMap.get('_id')); //this will fetch the query params
}
Angular's Location service should be used when interacting with the browser's URL and not for routing. Thats why we want to use Location service.
Angulars HttpParams are used to create query params. Remember HttpParams are immutable, meaning it has to be chained when creating the values.
At last, using this._location.replaceState to change to URL without reloading the page/route and native js location.path to get the url without params to reset the params every time.
constructor(
private _location: Location,
) {}
...
updateURLWithNewParamsWithoutReloading() {
const params = new HttpParams().appendAll({
price: 100,
product: 'bag'
});
this._location.replaceState(
location.pathname,
params.toString()
);
}
I've had an interesting situation where we used only one component for all routes we had. This is what routes looked like:
const routes: Routes = [
{
path: '',
component: HomeComponent,
children: [
{ path: 'companies', component: HomeComponent },
{ path: 'pipeline', component: HomeComponent },
// ...
]
},
// ...
];
So, basically, paths /, /companies and /pipeline were all having the same component that had to be loaded. And, since Angular prevents reloading of the components if they were previously loaded in the DOM, Router's navigate method returned a Promise that always resolved with null.
To avoid this, I had to use onSameUrlNavigation. By setting this value to 'reload', I managed to make the router navigate to the same URL with the updated query string parameters:
#NgModule({
imports: [RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload' })],
exports: [RouterModule]
})
Also you can add BehaviorSubject like:
refresher$ = new BehaviorSubject(null);
I changed my code from that:
this.route.queryParamMap.subscribe(some code)
to:
combineLatest([
this.route.queryParamMap,
this.refresher$
])
.pipe(
map((data) => data[0])
)
.subscribe(here is your the same code)
And when you need refresh your subscription, you need call this:
this.refresher$.next(null);
Also don't forget add unsubscribe from that to ngOnDestroy

Angular 9 : Allow trailing slash with optional parameter value in routes

We have below requirement for optional parameter. Routing is not matching with current URL. There are different cases of Parameter value. Parameter value can be blank. What we can change in below routing code?
Below are the request URL cases.
http://localhost:4200/act/sso/app/2040/token/7d2f-4ddd-924f-3fd36572/address/chd/city/chd/state/chd/zip/94524/tax/1000/rep1/ianchi/rep1Email/ianchi#am.com/rep2/Ryan/rep2Email/raphael#am.com
http://localhost:4200/act/sso/app/2040/token/7d2f-4ddd-924f-3fd36572/address/pkl/city/phonix/state/ca/zip/90401/tax/600/rep1//rep1Email//rep2//rep2Email/
http://localhost:4200/act/sso/app/2040/token/7d2f-4ddd-924f-3fd36572/address//city//state//zip//tax//rep1/ianchi/rep1Email/ianchi#am.com/rep2/Ryan/rep2Email/raphael#am.com
I am using below code in app-routing.module.ts file.
{
path: 'act/sso/app/:app/token/:token/address/:address/city/:city/state/:state/zip/:zip/tax/:tax/rep1/:rep1/rep1Email/:rep1Email/rep2/:rep2/rep2Email/:rep2Email',
component: SSOComponent
},
Please help on this?
Parameter value can be blank
If that would be the case, use Angular's Query Parameters instead of Router Parameters -- With that, you need to send an object inside the URL which Angular will parse in.
Attached Stackblitz Demo for your reference
Route
{
path: 'sso',
component: SSOComponent
},
Template from another component
<a [routerLink]="sso"
[queryParams]="ssoParams">SSO</a>
or inside it's component
#Component({...})
export class OtherComponent {
ssoParams = {
app: 1,
token: 123,
address: 'random'
}
constructor(private router: Router) {}
// or you can also redirect it inside the component
redirect(): void {
this.router.navigate(['sso'], { queryParams: this.ssoParams })
}
}
When redirected, the url will now be:
/sso?app=1&token=123&address=random
If it's empty or if you have passed an empty value on those objects, the URL which angular will parse in will only turn to like this, which is still valid:
/sso?app=&token=&address=
SSO Component
#Component({...})
export class SSOComponent {
constructor(private route: ActivatedRoute) {}
ngOnInit(): void {
// fetch the query parameters via subscribe
this.route.queryParams.subscribe(params => console.log(params))
// or to fetch the query parameters directly via object
// which this will contain: {app: 1, token: 123, address: 'random'}
console.log(this.route.snapshot.queryParams);
}
}

How to set URL query params in Vue with Vue-Router

I am trying to set query params with Vue-router when changing input fields, I don't want to navigate to some other page but just want to modify url query params on the same page, I am doing like this:
this.$router.replace({ query: { q1: "q1" } })
But this also refreshes the page and sets the y position to 0, ie scrolls to the top of the page. Is this the correct way to set the URL query params or is there a better way to do it.
Edited:
Here is my router code:
export default new Router({
mode: 'history',
scrollBehavior: (to, from, savedPosition) => {
if (to.hash) {
return {selector: to.hash}
} else {
return {x: 0, y: 0}
}
},
routes: [
.......
{ path: '/user/:id', component: UserView },
]
})
Here is the example in docs:
// with query, resulting in /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})
Ref: https://router.vuejs.org/en/essentials/navigation.html
As mentioned in those docs, router.replace works like router.push
So, you seem to have it right in your sample code in question. But I think you may need to include either name or path parameter also, so that the router has some route to navigate to. Without a name or path, it does not look very meaningful.
This is my current understanding now:
query is optional for router - some additional info for the component to construct the view
name or path is mandatory - it decides what component to show in your <router-view>.
That might be the missing thing in your sample code.
EDIT: Additional details after comments
Have you tried using named routes in this case? You have dynamic routes, and it is easier to provide params and query separately:
routes: [
{ name: 'user-view', path: '/user/:id', component: UserView },
// other routes
]
and then in your methods:
this.$router.replace({ name: "user-view", params: {id:"123"}, query: {q1: "q1"} })
Technically there is no difference between the above and this.$router.replace({path: "/user/123", query:{q1: "q1"}}), but it is easier to supply dynamic params on named routes than composing the route string. But in either cases, query params should be taken into account. In either case, I couldn't find anything wrong with the way query params are handled.
After you are inside the route, you can fetch your dynamic params as this.$route.params.id and your query params as this.$route.query.q1.
Without reloading the page or refreshing the dom, history.pushState can do the job.
Add this method in your component or elsewhere to do that:
addParamsToLocation(params) {
history.pushState(
{},
null,
this.$route.path +
'?' +
Object.keys(params)
.map(key => {
return (
encodeURIComponent(key) + '=' + encodeURIComponent(params[key])
)
})
.join('&')
)
}
So anywhere in your component, call addParamsToLocation({foo: 'bar'}) to push the current location with query params in the window.history stack.
To add query params to current location without pushing a new history entry, use history.replaceState instead.
Tested with Vue 2.6.10 and Nuxt 2.8.1.
Be careful with this method!
Vue Router don't know that url has changed, so it doesn't reflect url after pushState.
Actually you can push query like this: this.$router.push({query: {plan: 'private'}})
Based on: https://github.com/vuejs/vue-router/issues/1631
Okay so i've been trying to add a param to my existing url wich already have params for a week now lol,
original url: http://localhost:3000/somelink?param1=test1
i've been trying with:
this.$router.push({path: this.$route.path, query: {param2: test2} });
this code would juste remove param1 and becomes
http://localhost:3000/somelink?param2=test2
to solve this issue i used fullPath
this.$router.push({path: this.$route.fullPath, query: {param2: test2} });
now i successfully added params over old params nd the result is
http://localhost:3000/somelink?param1=test1&param2=test2
If you are trying to keep some parameters, while changing others, be sure to copy the state of the vue router query and not reuse it.
This works, since you are making an unreferenced copy:
const query = Object.assign({}, this.$route.query);
query.page = page;
query.limit = rowsPerPage;
await this.$router.push({ query });
while below will lead to Vue Router thinking you are reusing the same query and lead to the NavigationDuplicated error:
const query = this.$route.query;
query.page = page;
query.limit = rowsPerPage;
await this.$router.push({ query });
Of course, you could decompose the query object, such as follows, but you'll need to be aware of all the query parameters to your page, otherwise you risk losing them in the resultant navigation.
const { page, limit, ...otherParams } = this.$route.query;
await this.$router.push(Object.assign({
page: page,
limit: rowsPerPage
}, otherParams));
);
Note, while the above example is for push(), this works with replace() too.
Tested with vue-router 3.1.6.
Here's my simple solution to update the query params in the URL without refreshing the page. Make sure it works for your use case.
const query = { ...this.$route.query, someParam: 'some-value' };
this.$router.replace({ query });
My solution, no refreshing the page and no error Avoided redundant navigation to current location
this.$router.replace(
{
query: Object.assign({ ...this.$route.query }, { newParam: 'value' }),
},
() => {}
)
this.$router.push({ query: Object.assign(this.$route.query, { new: 'param' }) })
You could also just use the browser window.history.replaceState API. It doesn't remount any components and doesn't cause redundant navigation.
window.history.replaceState(null, '', '?query=myquery');
More info here.
For adding multiple query params, this is what worked for me (from here https://forum.vuejs.org/t/vue-router-programmatically-append-to-querystring/3655/5).
an answer above was close … though with Object.assign it will mutate this.$route.query which is not what you want to do … make sure the first argument is {} when doing Object.assign
this.$router.push({ query: Object.assign({}, this.$route.query, { newKey: 'newValue' }) });
To set/remove multiple query params at once I've ended up with the methods below as part of my global mixins (this points to vue component):
setQuery(query){
let obj = Object.assign({}, this.$route.query);
Object.keys(query).forEach(key => {
let value = query[key];
if(value){
obj[key] = value
} else {
delete obj[key]
}
})
this.$router.replace({
...this.$router.currentRoute,
query: obj
})
},
removeQuery(queryNameArray){
let obj = {}
queryNameArray.forEach(key => {
obj[key] = null
})
this.setQuery(obj)
},
I normally use the history object for this. It also does not reload the page.
Example:
history.pushState({}, '',
`/pagepath/path?query=${this.myQueryParam}`);
The vue router keeps reloading the page on update, the best solution is
const url = new URL(window.location);
url.searchParams.set('q', 'q');
window.history.pushState({}, '', url);
With RouterLink
//With RouterLink
<router-link
:to="{name:"router-name", prams:{paramName: paramValue}}"
>
Route Text
</router-link>
//With Methods
methods(){
this.$router.push({name:'route-name', params:{paramName: paramValue}})
}
With Methods
methods(){
this.$router.push({name:'route-name', params:{paramName, paramValue}})
}
This is the equivalent using the Composition API
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
router.push({ path: 'register', query: { plan: 'private' }})
</script>
You can also use the Vue devtools just to be sure that it's working as expected (by inspecting the given route you're on) as shown here: https://stackoverflow.com/a/74136917/8816585
Update
That will meanwhile mount/unmount components. Some vanilla JS solution is still the best way to go for that purpose.

Angular 2: How do I get params of a route from outside of a router-outlet

Similar question to Angular2 Get router params outside of router-outlet but targeting the release version of Angular 2 (so version 3.0.0 of the router). I have an app with a list of contacts and a router outlet to either display or edit the selected contact. I want to make sure the proper contact is selected at any point (including on page load), so I would like to be able to read the "id" param from the route whenever the route is changed.
I can get my hands on routing events by subscribing to the router's events property, but the Event object just gives me access to the raw url, not a parsed version of it. I can parse that using the router's parseUrl method, but the format of this isn't particularly helpful and would be rather brittle, so I'd rather not use it. I've also looked all though the router's routerState property in the routing events, but params is always an empty object in the snapshot.
Is there an actual straight forward way to do this that I've just missed? Would I have to wrap the contact list in a router-outlet that never changes to get this to work, or something like that?
If any body was looking for the latest solution of this issue (angular 8) I stumbled upon this article which worked very well for me.
https://medium.com/#eng.ohadb/how-to-get-route-path-parameters-in-an-angular-service-1965afe1470e
Obviously you can do the same implementation straight in a component outside the router outlet and it should still work.
export class MyParamsAwareService {
constructor(private router: Router) {
this.router.events
.pipe(
filter(e => (e instanceof ActivationEnd) && (Object.keys(e.snapshot.params).length > 0)),
map(e => e instanceof ActivationEnd ? e.snapshot.params : {})
)
.subscribe(params => {
console.log(params);
// Do whatever you want here!!!!
});
}
In the hope to spare the same struggle I went through.
I've been struggling with this issue for the whole day, but I think I finally figured out a way on how to do this by listening to one of the router event in particular. Be prepared, it's a little bit tricky (ugly ?), but as of today it's working, at least with the latest version of Angular (4.x) and Angular Router (4.x). This piece of code might not be working in the future if they change something.
Basically, I found a way to get the path of the route, and then to rebuild a custom parameters map by myself.
So here it is:
import { Component, OnInit } from '#angular/core';
import { Router, RoutesRecognized } from '#angular/router';
#Component({
selector: 'outside-router-outlet',
templateUrl: './outside-router-outlet.component.html',
styleUrls: ['./outside-router-outlet.component.css']
})
export class OutSideRouterOutletComponent implements OnInit {
path: string;
routeParams: any = {};
constructor(private router: Router) { }
ngOnInit() {
this.router.events.subscribe(routerEvent => {
if (routerEvent instanceof RoutesRecognized) {
this.path = routerEvent.state.root['_routerState']['_root'].children[0].value['_routeConfig'].path;
this.buildRouteParams(routerEvent);
}
});
}
buildRouteParams(routesRecognized: RoutesRecognized) {
let paramsKey = {};
let splittedPath = this.path.split('/');
splittedPath.forEach((value: string, idx: number, arr: Array<string>) => {
// Checking if the chunk is starting with ':', if yes, we suppose it's a parameter
if (value.indexOf(':') === 0) {
// Attributing each parameters at the index where they were found in the path
paramsKey[idx] = value;
}
});
this.routeParams = {};
let splittedUrl = routesRecognized.url.split('/');
/**
* Removing empty chunks from the url,
* because we're splitting the string with '/', and the url starts with a '/')
*/
splittedUrl = splittedUrl.filter(n => n !== "");
for (let idx in paramsKey) {
this.routeParams[paramsKey[idx]] = splittedUrl[idx];
}
// So here you now have an object with your parameters and their values
console.log(this.routeParams);
}
}

Categories