#configurerouter
Explore tagged Tumblr posts
Link
Hello,
#Reset #Netgear #range #extender is a very easy but sometimes we do the wrong with extender. but don't worry. Today, i will tell you that How to Reset Netgear Range Extender.
1 note
·
View note
Video
youtube
LEARN THE BASICS ON HOW TO CONFIGURE A ROUTER
#basics#learnthebasics#howtoconfigure#router#configurerouter#ipaddress#internet#wan#lan#wideareanetwork#localareanetwork#internetaccess
0 notes
Text
Upgrading your AngularJS application to Angular
I am a full stack developer which, for quite a long time, meant for me working mainly on the back end part of the application and touching the front end only to either reuse some components prepared by the front end team, or to make, let’s call it, a dummy view and… well you guessed it leave it for the front end team to make it more sensible. Back then I was living a joyful life not really caring about all the frameworks, bundlers and other stuff used to make the app’s appeal. But nothing lasts for ever and finally, due to some staff rotation (that’s a great euphemism), I was maintaining and developing pretty much everything, which obviously included also the dreaded front.
Since now I was sort of in charge I thought it would be a great idea to at least try to modernise everything that could be modernised. As the app predates Angular it was developed mainly in AngularJS (actually it was a mixture of many different technologies - I guess every programmer working on the code added something that excited him at that moment, leaving really diverse environment) so my best idea was upgrading it to… Angular.
In this post I’ll try to explain what I actually did, how you can upgrade your app from AngularJS to Angular, how to use Angular components within AngularJS components and vice versa and how I resolved routing issues.
It begins with a simple step
Actually there are many articles and posts on upgrading AngularJS to Angular (e.g. Victor Savkin’s Migrating Angular 1 Applications to Latest Angular in 5 Simple Steps). Also the official Angular documentation can be of use. I am not a pioneer here, but I have some experience in upgrading actual application.
First thing you will discover when you start digging is that you don’t really need to upgrade old code to upgrade your app. Angular provides UpgradeModule which is an NgModule allowing you to transform your app into a hybrid running both AngularJS and Angular code.
Simple, right?
Well… if you are lucky enough and the structure of your AngularJS code is… structured (i.e. you’ve got your components, directives, controllers, services and factories imported and declared in modules that are exported and then further imported in parent modules all the way down to the root module) without any quirks and other exotic features then you are ready to go. Otherwise you need to work on that first.
Next step is creating an Angular app - root module will be sufficient for start:
import {NgModule, Component} from ’@angular/core’; import {BrowserModule} from ’@angular/platform-browser’; import {UpgradeModule} from ’@angular/upgrade/static’; @NgModule({ imports: [ BrowserModule, UpgradeModule ], bootstrap: [AppComponent], declarations: [AppComponent] }) export class AngularAppModule { constructor(public upgrade: UpgradeModule) { } }
It is important not to forget to inject UpgradeModule in constructor as it does most of the magic!
And finally bootstrapping:
import {platformBrowserDynamic} from ’@angular/platform-browser-dynamic’; import {AngularJSAppModule} from ’./angular-js-app’; import {AngularAppModule} from ’./angular-app’; platformBrowserDynamic().bootstrapModule(TaxCubeNg2Module).then((ref) => { ref.instance.upgrade.bootstrap(document.body, [AngularJSAppModule.name]); });
With the above code the AngularJS application will be bootstrapped within the Angular application and both apps will run in parallel. Especially in case of big applications this is a great starting point as you don’t need to rewrite entire code to enjoy features of the newer framework and migrate your old code gradually (or even leave it as is).
Steep route
Of course this isn’t the end of the story. Not yet at least. The first issue I had after bootstrapping both apps (except for bundling it, but bundler’s configuration is a material for a different post, as it was specific for some choices that were made in terms of bundler itself and some configurations and optimisations made in the past) was fixing routes as no matter what address I typed in the browser it was always redirecting me to the AngularJS landing site in the best case scenario only flashing Angular view for a brief moment.
In general, if you create a hybrid app, at least for some time you are condemned to use two routers, i.e. UI-Router and @angular/router, which means that in the content section of your app (and maybe in some sidebars, headers and footers) you’ll have those two one right next to another:
<div class="content-section"> <div></div> </div>
Most of the articles suggests here creating a routing handling strategy and providing it in your Angular root module (routing handling strategy is a small class implementing UrlHandlingStrategy which, when provided, tells Angular’s router which of the URL’s should it support). This maybe useful as you don’t really need both of them to work at the same time but actually it didn’t fix the problem I came across. No matter what I typed into my routing handling strategy it didn’t exactly gag UI-Router. It was like one of my exes, it always wanted to have the last word and always when it got URL not matching its resources the sucker redirected to the landing site before the handling strategy even kicked in.
The solution to the above was actually a very simple trick, although as usually in such a cases I spent tons of time reading more and more articles and Stack Overflow threads and adding to my code couple dozens of lines to no avail. What I finally did was adding a new state in my $stateProvider in configureRoutes() function. I named it “ng2″ and added an empty template as the content view:
$stateProvider.state("ng2", { views: { "content@": { template: "" } } })
Moreover for the $urlRouterProvider I created custom otherwise function which redirected all the Angular app’s URLs to that state, showing nothing in ui-view and keeping UI-Router on the leash:
function otherwise($injector, $location) { $injector.invoke(["$state", ($state) => { const url = $location.url(); if (url === "" || url === "/") $state.go("main.app.home"); else if(url.toString().toLowerCase().includes("/AngularApp")) $state.go("ng2"); else $state.go("main.app.notFound"); }]); }
Upgrade - using AngularJS elements within the Angular code
So far I found three different cases of using AngularJS elements within my Angular code:
Simple one
If your directive or component is just a tag and you don’t need to pass any properties, e.g. you don’t bind to it any variables or functions then just use it as you’d do it in your AngularJS code, simply add the said tag in the HTML code. You’ll need also to add the
CUSTOM_ELEMENTS_SCHEMA const to your @NgModule schemas section, so Angular knows that you are using elements that weren’t explicitly declared, but that’s pretty much all you need:
@NgModule({ schemas: [ CUSTOM_ELEMENTS_SCHEMA ] }) export class AngularModule { }
Upgrading directives and components
Here it gets slightly more complicated. Angular cannot communicate directly with AngularJS elements so you’ll need to create a wrapper translating what you want to achieve to concepts better understood by Angular. Provided that your AngularJS directive looks something like this:
function angularJSDirective() { return { // ... scope: { firstInput: ">", secondInput: ">" } } };
You’ll need to create an Angular @Directive extending UpgradeComponent class:
import { Directive, ElementRef, Injector, Input } from '@angular/core'; import { UpgradeComponent } from '@angular/upgrade/static'; @Directive({ selector: 'upgraded-directive' // selector which you'll use in your HTML }) export class UpgradedDirective extends UpgradeComponent { @Input() firstInput: any; // possible be specific type @Input() secondInput: any; constructor(elementRef: ElementRef, injector: Injector) { super('angularJSDirective', elementRef, injector); } }
If you declare the above wrapper in your @NgModule you can use it like any other Angular directive.
The only catch here is that sometimes your AngularJS elements are dependant on AngularJS objects, e.g. $scope. This can be resolved by creating and declaring providers, e.g.:
export const ScopeProvider = { deps: ['$injector'], provide: '$scope', useFactory: ($injector: Injector) => $injector.get('$rootScope').$new(), };
Services (providers)
Similarly to the $scope provider mentioned above you can create wrappers for any of your AngularJS services.
const AngularJSProvider = { deps: ['$injector'], provide: 'angularJSService', useFactory: ($injector: Injector) => $injector.get('angularJSService'), };
Than declare it in the @NgModule in which you want to use it:
@NgModule({ providers: [ AngularJSProvider ] })
And simply inject it in the constructor.
constructor(@Inject('angularJSService') private angularJSService) { }
Downgrade - using Angular elements within the AngularJS code
In case of downgrading Angular elements the things are even simpler. You can use downgradeInjectable function and declare its result as a factory in the AngularJS module where you need it. Than use it as any other AngularJS service.
import { AngularService } from '/angular-modules/.../angular-service.service'; export const angularJSModule = module("angularJSModule", [ /*...*/]) //... .factory("angularService", downgradeInjectable(AngularService) as any);
I hope you enjoyed reading this post and it proved to be at least somewhat useful to you.
If you have any questions, comments or remarks regarding the above the comments section is yours.
0 notes
Text
Building Apps and Services with the Hapi.js Framework
Hapi.js is described as “a rich framework for building applications and services”. Hapi’s smart defaults make it a breeze to create JSON APIs, and its modular design and plugin system allow you to easily extend or modify its behavior.
The recent release of version 17.0 has fully embraced async and await, so you’ll be writing code that appears synchronous but is non-blocking and avoids callback hell. Win-win.
The Project
In this article, we’ll be building the following API for a typical blog from scratch:
# RESTful actions for fetching, creating, updating and deleting articles GET /articles articles#index GET /articles/:id articles#show POST /articles articles#create PUT /articles/:id articles#update DELETE /articles/:id articles#destroy # Nested routes for creating and deleting comments POST /articles/:id/comments comments#create DELETE /articles/:id/comments comments#destroy # Authentication with JSON Web Tokens (JWT) POST /authentications authentications#create
The article will cover:
Hapi’s core API: routing, request and response
models and persistence in a relational database
routes and actions for Articles and Comments
testing a REST API with HTTPie
authentication with JWT and securing routes
validation
an HTML View and Layout for the root route /.
The Starting Point
Make sure you’ve got a recent version of Node.js installed; node -v should return 8.9.0 or higher.
Download the starting code from here with git:
git clone https://github.com/markbrown4/hapi-api.git cd hapi-api npm install
Open up package.json and you’ll see that the “start” script runs server.js with nodemon. This will take care of restarting the server for us when we change a file.
Run npm start and open http://localhost:3000/:
[{ "so": "hapi!" }]
Let’s look at the source:
// server.js const Hapi = require('hapi') // Configure the server instance const server = Hapi.server({ host: 'localhost', port: 3000 }) // Add routes server.route({ method: 'GET', path: '/', handler: () => { return [{ so: 'hapi!' }] } }) // Go! server.start().then(() => { console.log('Server running at:', server.info.uri) }).catch(err => { console.log(err) process.exit(1) })
The Route Handler
The route handler is the most interesting part of this code. Replace it with the code below, comment out the return lines one by one, and test the response in your browser.
server.route({ method: 'GET', path: '/', handler: () => { // return [{ so: 'hapi!' }] return 123 return `<h1><marquee>HTML <em>rules!</em></marquee></h1>` return null return new Error('Boom') return Promise.resolve({ whoa: true }) return require('fs').createReadStream('index.html') } })
To send a response, you simply return a value and Hapi will send the appropriate body and headers.
An Object will respond with stringified JSON and Content-Type: application/json
String values will be Content-Type: text/html
You can also return a Promise or Stream.
The handler function is often made async for cleaner control flow with Promises:
server.route({ method: 'GET', path: '/', handler: async () => { let html = await Promise.resolve(`<h1>Google<h1>`) html = html.replace('Google', 'Hapi') return html } })
It’s not always cleaner with async though. Sometimes returning a Promise is simpler:
handler: () => { return Promise.resolve(`<h1>Google<h1>`) .then(html => html.replace('Google', 'Hapi')) }
We’ll see better examples of how async helps us out when we start interacting with the database.
The Model Layer
Like the popular Express.js framework, Hapi is a minimal framework that doesn’t provide any recommendations for the Model layer or persistence. You can choose any database and ORM that you’d like, or none — it’s up to you. We’ll be using SQLite and the Sequelize ORM in this tutorial to provide a clean API for interacting with the database.
SQLite comes pre-installed on macOS and most Linux distributions. You can check if it’s installed with sqlite -v. If not, you can find installation instructions at the SQLite website.
Sequelize works with many popular relational databases like Postgres or MySQL, so you’ll need to install both sequelize and the sqlite3 adapter:
npm install --save sequelize sqlite3
Let’s connect to our database and write our first table definition for articles:
// models.js const path = require('path') const Sequelize = require('sequelize') // configure connection to db host, user, pass - not required for SQLite const sequelize = new Sequelize(null, null, null, { dialect: 'sqlite', storage: path.join('tmp', 'db.sqlite') // SQLite persists its data directly to file }) // Here we define our Article model with a title attribute of type string, and a body attribute of type text. By default, all tables get columns for id, createdAt, updatedAt as well. const Article = sequelize.define('article', { title: Sequelize.STRING, body: Sequelize.TEXT }) // Create table Article.sync() module.exports = { Article }
Let’s test out our new model by importing it and replacing our route handler with the following:
// server.js const { Article } = require('./models') server.route({ method: 'GET', path: '/', handler: () => { // try commenting these lines out one at a time return Article.findAll() return Article.create({ title: 'Welcome to my blog', body: 'The happiest place on earth' }) return Article.findById(1) return Article.update({ title: 'Learning Hapi', body: `JSON API's a breeze.` }, { where: { id: 1 } }) return Article.findAll() return Article.destroy({ where: { id: 1 } }) return Article.findAll() } })
If you’re familiar with SQL or other ORM’s, the Sequelize API should be self explanatory, It’s built with Promises so it works great with Hapi’s async handlers too.
Note: using Article.sync() to create the tables or Article.sync({ force: true }) to drop and create are fine for the purposes of this demo. If you’re wanting to use this in production you should check out sequelize-cli and write Migrations for any schema changes.
Our RESTful Actions
Let’s build the following routes:
GET /articles fetch all articles GET /articles/:id fetch article by id POST /articles create article with `{ title, body }` params PUT /articles/:id update article with `{ title, body }` params DELETE /articles/:id delete article by id
Add a new file, routes.js, to separate the server config from the application logic:
// routes.js const { Article } = require('./models') exports.configureRoutes = (server) => { // server.route accepts an object or an array return server.route([{ method: 'GET', path: '/articles', handler: () => { return Article.findAll() } }, { method: 'GET', // The curly braces are how we define params (variable path segments in the URL) path: '/articles/{id}', handler: (request) => { return Article.findById(request.params.id) } }, { method: 'POST', path: '/articles', handler: (request) => { const article = Article.build(request.payload.article) return article.save() } }, { // method can be an array method: ['PUT', 'PATCH'], path: '/articles/{id}', handler: async (request) => { const article = await Article.findById(request.params.id) article.update(request.payload.article) return article.save() } }, { method: 'DELETE', path: '/articles/{id}', handler: async (request) => { const article = await Article.findById(request.params.id) return article.destroy() } }]) }
Import and configure our routes before we start the server:
// server.js const Hapi = require('hapi') const { configureRoutes } = require('./routes') const server = Hapi.server({ host: 'localhost', port: 3000 }) // This function will allow us to easily extend it later const main = async () => { await configureRoutes(server) await server.start() return server } main().then(server => { console.log('Server running at:', server.info.uri) }).catch(err => { console.log(err) process.exit(1) })
Continue reading %Building Apps and Services with the Hapi.js Framework%
via SitePoint https://ift.tt/2kzDM8P
0 notes