From 8fdb35504338a65bb1015b32852e58e22563c4bc Mon Sep 17 00:00:00 2001 From: Miroslav Jonas Date: Thu, 24 Aug 2017 10:57:33 +0200 Subject: [PATCH] feat: Extract StaticParserLoader and remove Http. Fixes (#64) --- LICENSE | 2 +- MIGRATION_GUIDE.md | 20 +++++--- README.md | 89 +++++++++++++---------------------- demo/cli/package.json | 4 +- package.json | 4 +- src/localize-router.module.ts | 27 ++--------- src/localize-router.parser.ts | 49 ++----------------- 7 files changed, 61 insertions(+), 134 deletions(-) diff --git a/LICENSE b/LICENSE index 08e3c71..2046ccb 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2016 Greentube +Copyright (c) 2017 Greentube Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: diff --git a/MIGRATION_GUIDE.md b/MIGRATION_GUIDE.md index 4d13069..13998d1 100644 --- a/MIGRATION_GUIDE.md +++ b/MIGRATION_GUIDE.md @@ -5,17 +5,24 @@ This guide is provided to make the transition as painless as possible. Steps to migrate your code are: - update the npm packages +- install new npm packages - update the module import Here is a detailed list of the changes that you need to make: 1. Update in your package.json `localize-router` to the latest 1.x version ([check the current release here](https://github.com/Greentube/localize-router/releases)). -2. Run `npm update` to update your packages. +2. If you were using `StaticParserLoader` you need to install [LocalizeRouterHttpLoader](https://github.com/Greentube/localize-router-http-loader): + + ```ts + npm install --save localize-router-http-loader + ``` + +3. Run `npm update` to update your existing packages. In some cases your local `node_modules` might get in broken state in which case you can try running `npm cache clean` or in worst cases deleting entire node_modules folder and running `npm install` again. -3. The module initialization `forRoot` method has changed a bit. Instead of loader, it expects an object of parameters. +4. The module initialization `forRoot` method has changed a bit. Instead of loader, it expects an object of parameters. ```ts import { Http } from '@angular/http'; @@ -37,26 +44,27 @@ In some cases your local `node_modules` might get in broken state in which case import { Http } from '@angular/http'; import { TranslateService } from '@ngx-translate/core'; import { Location } from '@angular/common'; - import { LocalizeRouterModule, LocalizeParser, StaticParserLoader, LocalizeRouterSettings } from 'localize-router'; + import { LocalizeRouterModule, LocalizeParser, LocalizeRouterSettings } from 'localize-router'; + import { LocalizeRouterHttpLoader } from 'localize-router-http-loader'; LocalizeRouterModule.forRoot(routes, { parser: { provide: LocalizeParser, useFactory: (translate, location, settings, http) => - new StaticParserLoader(translate, location, settings, http, 'your/path/to/config.json'), + new LocalizeRouterHttpLoader(translate, location, settings, http, 'your/path/to/config.json'), deps: [TranslateService, Location, LocalizeRouterSettings, Http] } }) ``` - You can now also provide additional settings regarding url prefixes and default language cache mechanisms: +5. You can now also provide additional settings to additionally configure the way `LocalizeRouter` loads and parses the routes: ```ts LocalizeRouterModule.forRoot(routes, { parser: { provide: LocalizeParser, useFactory: (translate, location, settings, http) => - new StaticParserLoader(translate, location, settings, http, 'your/path/to/config.json'), + new LocalizeRouterHttpLoader(translate, location, settings, http, 'your/path/to/config.json'), deps: [TranslateService, Location, LocalizeRouterSettings, Http] }, useCachedLang: { provide: USE_CACHED_LANG, useValue: booleanValue }, diff --git a/README.md b/README.md index 9db2e11..17c6839 100644 --- a/README.md +++ b/README.md @@ -12,8 +12,7 @@ Demo project can be found [here](https://github.com/meeroslav/localize-router-ex - [Installation](#installation) - [Usage](#usage) - [Initialize module](#initialize-module) - - [Static initialization](#static-initialization) - - [JSON config file](#json-config-file) + - [Http loader](#http-loader) - [Initialization config](#initialization-config) - [Manual initialization](#manual-initialization) - [Server side initialization](#server-side-initialization) @@ -46,43 +45,43 @@ In order to use `localize-router` you must initialize it with following informat ### Initialize module Module can be initialized either using static file or manually by passing necessary values. -#### Static initialization +#### Http loader + +In order to use Http loader for config files, you must include `localize-router-http-loader` package and use its `LocalizeRouterHttpLoader`. + ```ts import {BrowserModule} from "@angular/platform-browser"; import {NgModule} from '@angular/core'; import {HttpModule} from '@angular/http'; import {TranslateModule} from '@ngx-translate/core'; -import {LocalizeRouterModule} from 'localize-router/localize-router'; +import {LocalizeRouterModule} from 'localize-router'; +import {LocalizeRouterHttpLoader} from 'localize-router-http-loader'; import {RouterModule} from '@angular/router'; import {routes} from './app.routes'; @NgModule({ - imports: [ - BrowserModule, - HttpModule, - TranslateModule.forRoot(), - LocalizeRouterModule.forRoot(routes), - RouterModule.forRoot(routes) - ], - bootstrap: [AppComponent] -}) -export class AppModule { } -``` - -Static file's default path is `assets/locales.json`. You can override the path by calling `StaticParserLoader` on you own: -```ts -LocalizeRouterModule.forRoot(routes, { - parser: { + imports: [ + BrowserModule, + HttpModule, + TranslateModule.forRoot(), + LocalizeRouterModule.forRoot(routes, { + parser: { provide: LocalizeParser, useFactory: (translate, location, settings, http) => - new StaticParserLoader(translate, location, settings, http, 'your/path/to/config.json'), + new LocalizeRouterHttpLoader(translate, location, settings, http), deps: [TranslateService, Location, LocalizeRouterSettings, Http] - } + } + }), + RouterModule.forRoot(routes) + ], + bootstrap: [AppComponent] }) - +export class AppModule { } ``` +More details are available on [localize-router-http-loader](https://github.com/Greentube/localize-router-http-loader). + If you are using child modules or routes you need to initialize them with `forChild` command: ```ts @NgModule({ @@ -96,41 +95,22 @@ If you are using child modules or routes you need to initialize them with `forCh export class ChildModule { } ``` -#### JSON config file -JSON config file has following structure: -``` -{ - "locales": ["en", "de", ...], - "prefix": "MY_PREFIX" -} -``` - -```ts -interface ILocalizeRouterParserConfig { - locales: Array; - prefix?: string; -} -``` - -Prefix field is not mandatory and default value is empty string. - #### Initialization config Apart from providing routes which are mandatory, and parser loader you can provide additional configuration for more granular setting of `localize router`. More information at [LocalizeRouterConfig](#localizerouterconfig). #### Manual initialization -With manual initialization you need to provide information directly: -```ts -LocalizeRouterModule.forRoot(routes, { - parser: { - provide: LocalizeParser, - useFactory: (translate, location, settigns) => - new ManualParserLoader(translate, location, settings, ['en','de',...], 'YOUR_PREFIX'), - deps: [TranslateService, Location, LocalizeRouterSettings] - } -}) - -``` + With manual initialization you need to provide information directly: + ```ts + LocalizeRouterModule.forRoot(routes, { + parser: { + provide: LocalizeParser, + useFactory: (translate, location, settigns) => + new ManualParserLoader(translate, location, settings, ['en','de',...], 'YOUR_PREFIX'), + deps: [TranslateService, Location, LocalizeRouterSettings] + } + }) + ``` #### Server side initialization In order to use server side initialization in isomorphic/universal projects you need to create loader similar to this: @@ -153,7 +133,6 @@ export class LocalizeUniversalLoader extends LocalizeParser { export function localizeLoaderFactory(translate: TranslateService, location: Location, settings: LocalizeRouterSettings) { return new LocalizeUniversalLoader(translate, location, settings); } - ``` Don't forget to create similar loader for `ngx-translate` as well: @@ -217,7 +196,7 @@ Make sure you therefore place most common language (e.g. 'en') as a first string Sometimes you might have a need to have certain routes excluded from the localization process e.g. login page, registration page etc. This is possible by setting flag `skipRouteLocalization` on route's data object. -```typescript +```ts let routes = [ // this route gets localized { path: 'home', component: HomeComponent }, diff --git a/demo/cli/package.json b/demo/cli/package.json index 4091a3c..a1d574d 100644 --- a/demo/cli/package.json +++ b/demo/cli/package.json @@ -23,8 +23,8 @@ "@ngx-translate/core": "^7.0.0", "@ngx-translate/http-loader": "^0.1.0", "core-js": "^2.4.1", - "localize-router": "1.0.0-alpha.1", - "localize-router-http-loader": "0.0.1", + "localize-router": "1.0.0-alpha.3", + "localize-router-http-loader": "0.0.3", "rxjs": "^5.1.0", "zone.js": "^0.8.4" }, diff --git a/package.json b/package.json index 54fab77..d16eff0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "localize-router", - "version": "1.0.0-alpha.2", + "version": "1.0.0-alpha.3", "description": "An implementation of routes localization for Angular 2", "scripts": { "test": "karma start", @@ -36,7 +36,7 @@ "@angular/http": ">=2.0.0", "@angular/router": ">=3.0.0", "rxjs": "^5.0.0", - "@ngx-translate/core": "^6.0.0" + "@ngx-translate/core": ">=6.0.0" }, "devDependencies": { "@angular/animations": "~4.3.3", diff --git a/src/localize-router.module.ts b/src/localize-router.module.ts index 8d1fc85..d65382d 100644 --- a/src/localize-router.module.ts +++ b/src/localize-router.module.ts @@ -2,13 +2,12 @@ import { NgModule, ModuleWithProviders, APP_INITIALIZER, Optional, SkipSelf, Injectable, Injector } from '@angular/core'; -import { HttpModule, Http } from '@angular/http'; import { LocalizeRouterService } from './localize-router.service'; -import { LocalizeParser, StaticParserLoader } from './localize-router.parser'; +import { DummyLocalizeParser, LocalizeParser } from './localize-router.parser'; import { RouterModule, Routes } from '@angular/router'; import { LocalizeRouterPipe } from './localize-router.pipe'; -import { TranslateModule, TranslateService } from '@ngx-translate/core'; -import { Location, CommonModule } from '@angular/common'; +import { TranslateModule } from '@ngx-translate/core'; +import { CommonModule } from '@angular/common'; import { ALWAYS_SET_PREFIX, CACHE_MECHANISM, CACHE_NAME, DEFAULT_LANG_FUNCTION, LOCALIZE_ROUTER_FORROOT_GUARD, LocalizeRouterConfig, LocalizeRouterSettings, @@ -16,18 +15,6 @@ import { USE_CACHED_LANG } from './localize-router.config'; -/** - * Helper function for loading external parser - * @param translate - * @param location - * @param settings - * @param http - * @returns {StaticParserLoader} - */ -export function localizeLoaderFactory(translate: TranslateService, location: Location, settings: LocalizeRouterSettings, http: Http) { - return new StaticParserLoader(translate, location, settings, http); -} - @Injectable() export class ParserInitializer { parser: LocalizeParser; @@ -76,7 +63,7 @@ export function getAppInitializer(p: ParserInitializer, parser: LocalizeParser, } @NgModule({ - imports: [HttpModule, CommonModule, RouterModule, TranslateModule], + imports: [CommonModule, RouterModule, TranslateModule], declarations: [LocalizeRouterPipe], exports: [LocalizeRouterPipe] }) @@ -97,11 +84,7 @@ export class LocalizeRouterModule { { provide: CACHE_MECHANISM, useValue: config.cacheMechanism }, { provide: DEFAULT_LANG_FUNCTION, useValue: config.defaultLangFunction }, LocalizeRouterSettings, - config.parser || { - provide: LocalizeParser, - useFactory: localizeLoaderFactory, - deps: [TranslateService, Location, LocalizeRouterSettings, Http] - }, + config.parser || { provide: LocalizeParser, useClass: DummyLocalizeParser }, { provide: RAW_ROUTES, multi: true, diff --git a/src/localize-router.parser.ts b/src/localize-router.parser.ts index c431269..f74bfa3 100644 --- a/src/localize-router.parser.ts +++ b/src/localize-router.parser.ts @@ -1,5 +1,4 @@ import { Injectable } from '@angular/core'; -import { Http, Response } from '@angular/http'; import { Routes, Route } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; import { Observable } from 'rxjs/Observable'; @@ -12,14 +11,6 @@ import { CacheMechanism, LocalizeRouterSettings } from './localize-router.config const COOKIE_EXPIRY = 30; // 1 month -/** - * Config interface - */ -export interface ILocalizeRouterParserConfig { - locales: Array; - prefix?: string; -} - /** * Abstract class for parsing localization */ @@ -64,7 +55,7 @@ export abstract class LocalizeParser { this.routes = routes; - if (!this.locales.length) { + if (!this.locales || !this.locales.length) { return Promise.resolve(); } /** detect current language */ @@ -396,44 +387,10 @@ export class ManualParserLoader extends LocalizeParser { } } -/** - * Load configuration from server - */ -export class StaticParserLoader extends LocalizeParser { - private _dataLoaded: boolean; - - /** - * CTOR - * @param translate - * @param location - * @param settings - * @param http - * @param path - */ - constructor(translate: TranslateService, location: Location, settings: LocalizeRouterSettings, private http: Http, private path: string = 'assets/locales.json') { - super(translate, location, settings); - this._dataLoaded = false; - } - - /** - * Initialize or append routes - * @param routes - * @returns {Promise} - */ +export class DummyLocalizeParser extends LocalizeParser { load(routes: Routes): Promise { return new Promise((resolve: any) => { - if (this._dataLoaded) { - this.init(routes).then(resolve); - } else { - this.http.get(`${this.path}`) - .map((res: Response) => res.json()) - .subscribe((data: ILocalizeRouterParserConfig) => { - this._dataLoaded = true; - this.locales = data.locales; - this.prefix = data.prefix || ''; - this.init(routes).then(resolve); - }); - } + this.init(routes).then(resolve); }); } }