惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cloudbric
Cloudbric
T
Threat Research - Cisco Blogs
Simon Willison's Weblog
Simon Willison's Weblog
AWS News Blog
AWS News Blog
P
Privacy & Cybersecurity Law Blog
H
Help Net Security
云风的 BLOG
云风的 BLOG
G
GRAHAM CLULEY
Spread Privacy
Spread Privacy
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
A
Arctic Wolf
Project Zero
Project Zero
Engineering at Meta
Engineering at Meta
P
Privacy International News Feed
Blog — PlanetScale
Blog — PlanetScale
Stack Overflow Blog
Stack Overflow Blog
M
MIT News - Artificial intelligence
The Register - Security
The Register - Security
Recorded Future
Recorded Future
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Cisco Blogs
PCI Perspectives
PCI Perspectives
Recent Announcements
Recent Announcements
Martin Fowler
Martin Fowler
A
About on SuperTechFans
W
WeLiveSecurity
GbyAI
GbyAI
V
Vulnerabilities – Threatpost
The GitHub Blog
The GitHub Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Check Point Blog
Y
Y Combinator Blog
月光博客
月光博客
Scott Helme
Scott Helme
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google DeepMind News
Google DeepMind News
F
Fortinet All Blogs
U
Unit 42
G
Google Developers Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Threatpost
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Google Online Security Blog
Google Online Security Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Cisco Talos Blog
Cisco Talos Blog
博客园 - 三生石上(FineUI控件)
Hugging Face - Blog
Hugging Face - Blog
MongoDB | Blog
MongoDB | Blog
博客园 - 司徒正美

Minko Gechev's blog

skillgrade Unit Tests for AI Agent Skills You Should Care About AI Generative Development LLM-first Web Framework Reactive framework in ~200 lines of JavaScript Managing Angular Are LLMs going to replace us? Prefetching Heuristics Design Patterns in Open Source Projects - Part II Design Patterns in Open Source Projects - Part I What I learned doing 125 public talks - Part I Dynamic imports solve all the problems, right? 5 Angular CLI Features You Didn't Know About Angular quicklink Preloading Strategy Introducing Bazel Schematics for Angular CLI Building TypeScript Projects with Bazel Joining Google Playing Mortal Kombat with TensorFlow.js. Transfer learning and data augmentation Fast, extensible, configurable, and beautiful linter for Go Introducing Guess.js - a toolkit for enabling data-driven user-experiences on the Web Machine Learning-Driven Bundling. The Future of JavaScript Tooling. JavaScript Decorators for Declarative and Readable Code 3 Tricks For Using Redux and Immutable.js with TypeScript Follow Your Dream Career with Open Source. Personal Story. Redux Anti-Patterns - Part 1. State Management. Faster Angular Applications - Understanding Differs. Developing a Custom IterableDiffer Faster Angular Applications - Part 2. Pure Pipes, Pure Functions and Memoization Faster Angular Applications - Part 1. On Push Change Detection and Immutability Understanding Dynamic Scoping and TemplateRef Implementing a Simple Compiler on 25 Lines of JavaScript Developing Statically Typed Programming Language WebVR for a Gamified IDE 7 Angular Tools That You Should Consider Announcing ngrev - Reverse Engineering Tool for Angular Implementing Angular's Dependency Injection in React. Understanding Element Injectors. Distributing an Angular Library - The Brief Guide Angular in Production Ahead-of-Time Compilation in Angular 2.5X Smaller Angular 2 Applications with Google Closure Compiler Using Stripe with Angular (Deprecated) Building an Angular Application for Production Implementing the Missing "resolve" Feature of the Angular 2 Router Scalable Single-Page Application Architecture Managing ambient type definitions and dealing with the "Duplicate identifier" TypeScript error Static Code Analysis of Angular 2 and TypeScript Projects Enforcing Best Practices with Static Code Analysis of Angular 2 Projects ViewChildren and ContentChildren in Angular Angular 2 Hot Loader Lazy Loading of Route Components in Angular 2 Aspect-Oriented Programming in JavaScript Flux in Depth. Store and Network Communication. Using JSX with TypeScript Flux in Depth. Overview and Components. Even Faster AngularJS Data Structures Boost the Performance of an AngularJS Application Using Immutable Data - Part 2 Angular2 - First Impressions Build Your own Simplified AngularJS in 200 Lines of JavaScript Persistent State of ReactJS Component Boost the Performance of an AngularJS Application Using Immutable Data Processing Binary Protocols with Client-Side JavaScript Stream your Desktop to HTML5 Video Element Multi-User Video Conference with WebRTC Asynchronous calls with ES6 generators Binary Tree iterator with ES6 generators WebRTC chat with React.js AngularJS in Patterns (Part 3) AngularJS in Patterns (Part 2). Services. Using GitHub Pages with Jekyll! AngularJS in Patterns (Part 1). Overview of AngularJS Singleton in JavaScript Express over HTTPS What I get from the JavaScript MV* frameworks Remote Desktop Client with AngularJS and Yeoman The magic of $resource (or simply a client-side Active Record) AngularJS Inheritance Patterns AngularAOP v0.1.0 Advanced JavaScript at Sofia University AngularJS style guide Lazy prefetching of AngularJS partials VNC client on 200 lines of JavaScript Aspect-Oriented Programming with AngularJS CSS3 flipping effect Practical programming with JavaScript Why I should use publish/subscribe in JavaScript JavaScript, the weird parts Functional programming with JavaScript plainvm Looking for performance? Probably you should NOT use [].sort (V8) JavaScript image scaling ELang Caching CSS with localStorage Self-invoking functions in JavaScript (or Immediately Invoked Function Expressions) Asus N56VZ + Ubuntu 12.04 (en) Asus N56VZ + Ubuntu 12.04 Debian Squeeze + LXDE on Google Nexus S (or having some fun while suffering) HTML5 image editor Курсови проекти – ФМИ Carousel Gallery SofiaJS...
Dynamically Configuring the Angular's Router
2015-12-30 · via Minko Gechev's blog

Warning: This version of the Angular 2 router is now deprecated! This means that soon the used below APIs will no longer be available.

A couple of months ago I wrote “Lazy Loading of Route Components in Angular 2”, where I explained how we can take advantage of the AsyncRoutes and the virtual proxy pattern in Angular 2.

This way we can incrementally load the entire application by only requesting the resources required for the individual views. As result we will decrease the initial load time, which will dramatically improve the user’s experience.

The code for this article is available at my GitHub account.

Problem

This strategy works great! The only things that we need to provide to the AsyncRoute definition are name, path and a loader.

Inside of the loader function we can have whatever custom logic we want to. The only contract that we sign with the framework is that the loader needs to return a promise:

@RouteConfig([
  { path: '/', component: Home, name: 'home' },
  new AsyncRoute({
    path: '/about',
    loader: () => System.import('./components/about/about').then(m => m.About),
    name: 'about'
  })
])

But what if we receive the routes definitions from a remote service and we don’t have them during initialization time?

Well, in such case we need to solve the following three problems:

Referencing not registered routes inside of a template

If we want to reference to a route which is not declared within @RouteConfig by using:

<a [routeLink]="['/not-registered']">Not registered</a>

We will get a runtime error. This means that we need to implement a behavior in which we can list the available at given point of time routes.

Updating the @RouteConfig’s metadata

This is required for consistency. Since the way we register routes in Angular 2 is by using @RouteConfig, we need to make sure that it’s always up-to-date, with all the routes available.

Dynamically registering routes

We need to make the framework aware of the new route definition that we received from the remote service. For this purpose we need to play with the router’s internals, in order to provide the instructions for loading the new route.

Solution

Lets start by exploring the solution of the first problem:

Dynamically rendering the application’s navigation

We can define a component called AppNav which receives a list of objects of the type { name: "Route name", path: ['/Route', 'Path'] } and renders the navigation:

@Component({
  selector: 'app-nav',
  directives: [ROUTER_DIRECTIVES],
  template: `
    <nav>
      <a *ngFor="#route of routes"
        [routerLink]="route.path">
        {{route.name}}
      </a>
    </nav>
  `
})
export class AppNav {
  @Input()
  routes: string[];
}

The component above has a single @Input called routes and uses the ROUTER_DIRECTIVES because of the routerLink directive. Once the routes property changes its template will be populated with the passed value.

We can use this component in the following way:

<app-nav [routes]="[
  { name: 'Route 1', path: ['/Path1'] },
  { name: 'Route 2', path: ['/Path2'] }
]"></app-nav>

So far so good! Now lets see how we can get the list of registered routes and pass them to the directive!

Messing around with the @RouteConfig’s metadata

Lets peek at the semantics of the @RouteConfig decorator. All it does is to add another item to the array of annotations stored as metadata associated with given component. This means that by using the Reflect API we can get all the registered routes!

In order to have better separation of concerns we can isolate the logic for configuring the dynamic routes into a separate class. Lets define a class called DynamicRouteConfigurator, which has the following API:

@Injectable()
class DynamicRouteConfigurator {
  constructor(private registry: RouteRegistry) {}
  // Gets the list of registered with @RouteConfig routes
  // associated with given `component`
  getRoutes(component: Type) {...}
  // Updates the metadata added by @RouteConfig associated
  // with given `component`
  updateRouteConfig(component: Type, routeConfig) {...}
  // Adds additional `route` to given `component`
  addRoute(component: Type, route) {...}
}

Now lets define a root component which uses the AppNav component and DynamicRouteConfigurator service we defined:

@Component({
  selector: 'app',
  viewProviders: [DynamicRouteConfigurator],
  templateUrl: './components/app/app.html',
  styleUrls: ['./components/app/app.css'],
  encapsulation: ViewEncapsulation.None,
  directives: [AppNav, ROUTER_DIRECTIVES]
})
@RouteConfig([
  { path: '/', component: HomeCmp, as: 'Home' }
])
export class AppCmp {
  appRoutes: string[][];
  constructor(private dynamicRouteConfigurator: DynamicRouteConfigurator) {...}
  private getAppRoutes(): string[][] {}
}

Now lets explore the definition of getRoutes:

Getting the registered routes

getRoutes(component: Type) {
  return Reflect.getMetadata('annotations', component)
    .filter(a => {
      return a.constructor.name === 'RouteConfig';
    }).pop();
}

Above we simply get all the annotations associated with the passed as argument component and extract the declared routes.

Updating the registered routes

The implementation of updateRouteConfig is quite simple as well:

updateRouteConfig(component: Type, routeConfig) {
  let annotations = Reflect.getMetadata('annotations', component);
  let routeConfigIndex = -1;
  for (let i = 0; i < annotations.length; i += 1) {
    if (annotations[i].constructor.name === 'RouteConfig') {
      routeConfigIndex = i;
      break;
    }
  }
  if (routeConfigIndex < 0) {
    throw new Error('No route metadata attached to the component');
  }
  annotations[routeConfigIndex] = routeConfig;
  Reflect.defineMetadata('annotations', annotations, AppCmp);
}

We loop over all the annotations in order to find the index of the metadata added by the @RouteConfig decorator and when we find it, we update its value. Right after that we update the annotations using Reflect.defineMetadata(...).

Updating the navigation

We already have the definition of the AppNav component! Now we can get the registered with @RouteConfig routes and render links to all of them.

We can populate the list with the links to the routes using the AppNav component, by setting the appRoutes’ value:

constructor(private dynamicRouteConfigurator: DynamicRouteConfigurator) {
  this.appRoutes = this.getAppRoutes();
  // ...
}

Dynamically registering new routes

Now lets try to asynchronously add another route! We can notice that the DynamicRouteConfigurator has a method called addRoute, so lets use it:

constructor(private dynamicRouteConfigurator: DynamicRouteConfigurator) {
  this.appRoutes = this.getAppRoutes();
  setTimeout(_ => {
    let route = { path: '/about', component: AboutCmp, as: 'About' };
    this.dynamicRouteConfigurator.addRoute(this.constructor, route);
    this.appRoutes = this.getAppRoutes();
  }, 1000);
}

All we do above is to set a timeout for 1 second, define the About route and add it to the AppCmp using the injected instance of the DynamicRouteConfigurator. As last step we update the value of the appRoutes which will be reflected by the AppNav component.

Using the RouteRegistry

Now in order to get complete clarity of the entire implementation lets take a look at the addRoute method defined within the DynamicRouteConfigurator:

addRoute(component: Type, route) {
  let routeConfig = this.getRoutes(component);
  routeConfig.configs.push(route);
  this.updateRoutes(component, routeConfig);
  this.registry.config(component, route);
}

As first step we get all the registered routes associated with the target component by using getRoutes, later we append one additional route and we invoke the updateRouteConfig method. As last step we register the new route in order to make the framework aware of it. We register it by using the instance of the RouteRegister passed as dependency via the DI mechanism of the framework.

Conclusion

Another point for future improvement of the DynamicRouteConfigurator is to allow further modification of the route configuration, such as deletion of existing routes. Although the RouteRegistry allows this functionality we’ll need to touch private APIs (the _routes property of the RouteRegistry instances).