How do I match this in Backbone.js routes? - javascript

/story/:id
AND
/story/:id/:timestamp
I want both of these URLs to go to the same function in Backbone.js routes. (timestamp is optional)
What's the regex for this in Backbone.js?

Just define two routes:
routes: {
'story/:id': 'story',
'story/:id/:timestamp': 'story',
//...
}
The Backbone.Router.extend docs even include an example that is almost an exact match for your situation:
routes: {
//[...]
"search/:query": "search", // #search/kiwis
"search/:query/p:page": "search" // #search/kiwis/p7
},
And the routes documentation includes an example of a similar situation:
routes: {
//[...]
"folder/:name": "openFolder",
"folder/:name-:mode": "openFolder"
}

Related

Best way to check what page you're on in Vue.js

I have
these simple route/URL when I am in a car details page
http://localhost:8080/car/1
I am using vue2; what is the best way to check if I am on a car page?
I normally
would have checked for the first segment of the URL, but I wasn't sure if that is the best future-proof approach.
Questions
Should I use JS to detect what page I am ?
Should I use Vue functionality to access the router object?
Why would one decide to pick one over another?
You could provide a name for your route inside the routes definition like :
{
path: '/car/{id}',
name: 'car',
component: CarView
},
then access it using this.$route.name or you could parse the this.$route.path to get the name using String object methods
Perhaps, try using: router.currentRoute.path, where router is:
import Router from "vue-router";
Vue.use(Router);
const routes = [
{ path: "/", component: Home },
{ path: "/test1", component: Test1 },
{ path: "/test2", component: Test2 }
];
const router = new Router({
routes
});
console.log('Current route: ', router.currentRoute.path);

url changes but angular does not navigate

I have 2 links like below. When I click on any one the first time, it navigates to it but when I click on the second link after that, the url changes but it does not navigate to it.
<li><a routerLink="/order/buyer" >Buyer</a></li>
<li><a routerLink="/order/seller">Seller</a></li>
These are my route configuration:
app.routing.module.ts
const routes: Routes = [
{
path: '',
pathMatch: 'full',
component: RootComponent,
},
{
path: '',
children: [
{
path: 'order',
loadChildren: './order/order.module#OrderModule',
}
]
}
order.module.ts
export const ROUTES: Routes = [
{
path: ':orderParty/:id',
component: OrderDetailComponent,
canDeactivate: [OrderDetailGuardService]
},
{
path: ':orderParty',
component: OrderListComponent
}
];
Tried several things, that out there but didn't work. What I have noticed is on the second click, the ngOnInit() of the 'OrderListComponent' does not get called.
You have a few options to solve this common issue in Angular, the most common one is using the solution on this GitHub thread:
https://github.com/angular/angular/issues/13831#issuecomment-319634921
constructor(private router: Router){
// override the route reuse strategy
this.router.routeReuseStrategy.shouldReuseRoute = function(){
return false;
}
this.router.events.subscribe((evt) => {
if (evt instanceof NavigationEnd) {
// trick the Router into believing it's last link wasn't previously loaded
this.router.navigated = false;
// if you need to scroll back to top, here is the right place
window.scrollTo(0, 0);
}
});
}
Another solution would to subscribe to your router params and handle change based on the new param like this article suggests:
this.activeRoute.params.subscribe(routeParams => {
this.loadUserDetail(routeParams.id);
});
https://medium.com/#mvivek3112/reloading-components-when-change-in-route-params-angular-deed6107c6bb
Yes, because route is same its the dynamic parameter that is changing. to read changed parameter you can inject router in construct and read parameter like
this.router.params.subscribe((params)=>{console.log(params)});
The route is pointing to same component hence its not re initializing.

Defining Auth strategy using Glue

I am using glue to spin up the hapi server so I gave the json object with connection and registration details.
I have 10 routes and i need to use authentication strategy for all the 10 routes, So followed the below steps
1) I have registered the xyz custom auth plugin
2) Defined the strategy server.auth.strategy('xyz', 'xyz', { });
3) At every route level I am enabling auth strategy
auth: {
strategies: ['xyz'],
}
How can I give below line to glue configuration object itself.
server.auth.strategy('xyz', 'xyz', { });
Glue.compose(ServerConfig, { relativeTo: baseDir }, (err, server) => {
internals.server = server;
})
One more question here is, in this line server.auth.strategy('xyz', 'xyz', { from json file}); I am reading the JSON data from a config file. When I change the data in this JSON file I dont want to restart the server manually to load the modified data. Is there any plugin or custom code to achieve this?
I figured out a general workaround for when you want to do setup that Glue does not directly support (AFAIK) and you also don't want to keep adding to index.js.
Create a plugins folder where your manifest.js is located.
Create a file plugins/auth.js (in this case). Here you will have a register callback with access to the server object and you can make setup calls that go beyond what Glue does declaratively.
Add a plugin item to manifest.js pointing to your plugin file.
in manifest.js:
register: {
plugins: [
{
plugin: './plugins/auth',
},
]
}
in plugins/auth.js:
module.exports = {
name: 'auth',
async register (server) {
await server.register([
require('#hapi/cookie'),
]);
server.auth.strategy('session', 'cookie', {
cookie: {
name: 'sid-example',
password: '!wsYhFA*C2U6nz=Bu^%A#^F#SF3&kSR6',
isSecure: false
},
redirectTo: '/login',
validateFunc: async (request, session) => {
const account = await users.find(
(user) => (user.id === session.id)
);
if (!account) {
return { valid: false };
}
return { valid: true, credentials: account };
}
});
server.auth.default('session');
},
};
(auth setup code is from the Hapi docs at enter link description here)
This is the way I have found where I can call things like server.auth.strategy() sort-of from manifest.js.
Note: Auth is not a great example for this technique as there is a special folder for auth strategies in lib/auth/strategies.

Angular - How can I activate AUX route with lazy loaded module?

I have an angular app which is loading lazily module.
At first the app is navigating to home where it loads the module ( named module1) :
main routing :
const routes: Routes = [
{ path: "", redirectTo: "/home", pathMatch: "full" },
{ path: "home", loadChildren: "./module1/module1.module#Module1Module" },
];
At module1 - there's also routing table :
const routes: Routes = [
{
path: "", component: Home1Component,
children: [
{ path: 'bird', outlet: 'under', component: Home2Component }
]
}
];
So since it's loading lazily , when the app starts - it goes to /home where there it loads the Home1Component
But Home1Component also has a button in it which suppose to set a value to the outlet route .
home1.component.html:
<input value="click to activate aux route" type="button" (click)="go()"/>
<router-outlet ></router-outlet>
<router-outlet name='under'></router-outlet> //<---- I want to activate only this
This is how I try to activate the outlet route :
public go() {
this.router.navigate([{ outlets: { under: ['bird'] } }], { relativeTo: this.route })
}
But I get an error :
Error: Cannot match any routes. URL Segment: 'home'
Question :
Why am I getting this error and how can I fix it ?
Online code here : Stackblitz
Well with the help of #jmw5598 who referenced me to the problem/bug with the router .
There is a problem with default empty location for lazy loaded modules.
Here is a working solution for the problem .
The key thing to understand is that lazy modules should not have empty root path
Related specific description :

Matching query param in vue routes

Is there any way to route by a query param? I would like to match the following route: site.com/?foo=123. I've tried things like
{ path: '/\?foo=[\d]*' }
without success.
Unfortunately, you can't match a query param in the path string of a route definition.
Vue Router uses path-to-regexp, and its documentation says:
The RegExp returned by path-to-regexp is intended for use with pathnames or hostnames. It can not handle the query strings or fragments of a URL.
You can use regular expressions to match on a route param by specifying the regex in parenthesis after the param name like so:
{ path: '/:foo([\d]*)' },
But, Vue Router's route params can't be in the query.
Here are some examples of the different route-matching features Vue Router provides.
If you really need to check the query of the url, you could use the beforeEnter handler to match the query manually and then reroute if it isn't the correct format:
const routes = [{
name: 'home',
path: '/',
component: Home,
beforeEnter(to, from, next) {
if (to.query.foo && to.query.foo.match(/[\d]*/)) {
next({ name: 'foo', query: to.query });
} else {
next();
}
}
}, {
name: 'foo',
path: '/',
component: Foo,
}];

Categories