Mongodb Ionic Cannot Read Property Protype of Undefined

Introduction

This blog mail is role of the terminal project for the Udacity Machine Learning Engineer Nanodegree Plan using AWS SageMaker

The project contains simulated data that mimics customer beliefs on the Starbucks rewards mobile app. The goal of the project is to analyze this "historical" data in gild to implement an algorithm that finds the most suiting offer type for each customer.

The data is contained in three files:

  • portfolio.json - containing offer ids and meta data about each offer (duration, type, etc.)
  • contour.json - demographic data for each customer
  • transcript.json - records for transactions, offers received, offers viewed, and offers completed

Here is the schema and explanation of each variable in the files:

portfolio.json

  • id (cord) - offering id
  • offer_type (cord) - blazon of offering ie BOGO, disbelieve, informational
  • difficulty (int) - minimum required spend to consummate an offer
  • reward (int) - advantage given for completing an offer
  • elapsing (int) - time for offer to be open, in days
  • channels (list of strings)

profile.json

  • age (int) - historic period of the customer
  • became_member_on (int) - date when customer created an app account
  • gender (str) - gender of the client (annotation some entries contain 'O' for other rather than M or F)
  • id (str) - client id
  • income (float) - client's income

transcript.json

  • issue (str) - record description (ie transaction, offer received, offer viewed, etc.)
  • person (str) - customer id
  • time (int) - fourth dimension in hours since start of test. The data begins at time t=0
  • value - (dict of strings) - either an offering id or transaction corporeality depending on the tape

Solution Statement

This is a classification problem, my approach is going to be: create a Machine learning model to
predict the best offer for the user, for BOGO or disbelieve (we are going to leave out the
informational offers, which have no real "conversion")
At that place are the steps to follow:

  • Fetching data
  • Data Cleaning
  • Data Grooming
  • Data visualization and analysis
  • Railroad train Model
  • Evaluate the model

Evaluation Metrics

Since this is a classification trouble we can apply the post-obit metrics to evaluate the model:

  • Precision The proportion of positive cases that were correctly identified.
  • Recall The proportion of actual positive cases which are correctly identified.
  • F1-score, that combines the two previous measures.
  • Roc_auc_score Area Under the ROC Curve (AUC), a measure out that calculates the area
    under the Receiving Operating Feature Curve. This particular bend accounts that
    higher probabilities are associated with true positives and vice-versa.

Algorithms evaluated

Nosotros explored ii algorithms Linear Learner and XGBoost to find the all-time models for for each offering, a Discount, a Buy Ane Get One (BOGO)
or Informational.

Project pattern

During the fetching information process, we have to join all the dissimilar pieces of information coming
from the 3 data sources, we demand to fetch the data.

Data preparation. After analyzing the data, we transform the dataset through different stages
missing imputation, categories encoding, information standardization, etc.

Clean and Visualize the data to understand it's content and analyze it, to find possibles outliers
and remove them (if possible).

Information distribution visualization



Feature Engineering

Preprocessing with scikit-learn

  • Encode categorical variable gender (One Hot encoder)
  • Impute missing values
  • Normalize characteristic distributions

Things to observe:

  • In that location are three genre recorded in the dataset (F, 1000, O) which is going to be encoded during the feature technology phase.
  • The scatterplot shows some odd construction just it should be because the information was imitation, also it doesn't await to be outliers.

Railroad train the model

We used dissimilar ML models, one to predict the BOGO, the other to
predict the Disbelieve and another to predict the advisory offer. For each model, we try two algorithms, Linear Learner and Amazon Sage maker XG-Boost built in Algorithm.

For each algorithm, we tune the hyper-parameters to find the i with the best performance.
With the all-time two models, we can combine the results in guild to obtain a unmarried type of offering for
the user.

Evaluate the model we mensurate and compare the performances of the models with the
electric current benchmark, to learn if the proposed solution is viable for the offering attribution process.

Notebooks

The 3 notebooks and the data used for this projection can be establish in the following github repository:
https://github.com/jomendez/starbucks-captone-motorcar-learning.git

  • information-exploration.ipynb
  • feature_engineering.ipynb
  • training_the_model.ipynb

Results

What is the CSS Box Model.

CSS Box Model

When a spider web page is rendered, the browser's rendering engine will display each HTML elements as a rectangular box.

Every rectangle is equanimous of a margin, border, padding and the element. If you open google chrome browser'south console and inspect an element, go to the right column and roll down until you see a box.

css box model

How to summate the size of the box?

            width = content width + padding-left + padding-right + edge-left + border-correct  height = content elevation + padding-top + padding-bottom + border-superlative + border-button          

annotation: The margin doesn't touch on the size of the box, simply it affects other content interacting effectually the box.

You can control how the size of the box information technology calculated with box-sizing.
The box-sizing CSS holding sets how the total width and height of an element is calculated.

syntax:

box-sizing: content-box | border-box

Meet full example below for a ameliorate understanding.

Run into the Pen
Instance css model box by Jose Mendez (@jomendez)
on CodePen.

From the MDN:

Box model content area.

The content area, bounded past the content border, contains the "real" content of the element, such as text, an image, or a video player. Its dimensions are the content width (or content-box width) and the content tiptop (or content-box meridian). It often has a groundwork color or background image.

If the box-sizing property is gear up to content-box (default) and if the element is a cake element, the content area'southward size can be explicitly divers with the width, min-width, max-width, height, min-tiptop, and max-height properties.

Box model padding area.

The padding surface area, bounded by the padding edge, extends the content area to include the element'south padding. Its dimensions are the padding-box width and the padding-box pinnacle.

The thickness of the padding is determined past the padding-acme, padding-correct, padding-bottom, padding-left, and shorthand padding properties.

Box model edge expanse.

The border surface area, divisional by the border edge, extends the padding surface area to include the chemical element's borders. Its dimensions are the edge-box width and the border-box height.

The thickness of the borders are determined by the border-width and shorthand border properties. If the box-sizing property is set to border-box, the edge expanse's size can be explicitly defined with the width, min-width, max-width, height, min-pinnacle, and max-height properties. When there is a groundwork (background-color or background-image) attack a box, it extends to the outer edge of the border (i.eastward. extends underneath the border in z-ordering). This default behavior can be altered with the background-clip css belongings.

Box model margin area.

The margin surface area, bounded by the margin edge, extends the border surface area to include an empty expanse used to separate the element from its neighbors. Its dimensions are the margin-box width and the margin-box height.
he size of the margin area is adamant by the margin-superlative, margin-right, margin-bottom, margin-left, and shorthand margin properties. When margin collapsing occurs, the margin area is not clearly defined since margins are shared between boxes.

What if these values are non declared?

If margin, padding or borders are undeclared, they are either zero or the browser's default value.

Run into the box model with your ain optics.

You can visualize the box model in your page past opening the chrome programmer tool and audit the body of your page, add temporarely the post-obit code:

            * { border: 1px solid red !of import; }          

visualizing the css box model

Simplistic CRUD ionic 5 firestore TODO app instance

This is a very simplistic CRUD (Create, Read, Update, Delete) Created with ionic 5 and firestore (database).

You can download the source lawmaking here.

Note:
I used this pattern equally inspiration: https://dribbble.com/shots/4782162-To-Do-App-Concept-Minimal.

The idea here is to illustrate how to create a simple CRUD with firestore.

 Simplistic CRUD ionic 5 firestore TODO app example

Installation.

My advice is that you install nvm (to manage your node versions), hither is tutorial stride by step.

After you lot install nvm run the following commands:

            nvm install 12          

If everything went well you'll have installed node 12.0.0 .

Now yous'll need to install ionic cli:

            npm install -yard @ionic/cli          

At present is time to download the projection and install it's dependencies.

            git clone https://github.com/jomendez/ionic-v-grime-todo-with-firestore.git cd ionic-v-grime-todo-with-firestore npm install          

Side by side step it to create a config file that will incorporate your firebase config keys hither:

src/app/config/firebase.ts

If you are on bash you can utilise the following command:

            touch src/app/config/firebase.ts          

Assuming that you are familiar with firebase and already have an account, paste your configuration info into the firebase.ts file, it should looks something like this (This is just and example), If you are non familiar with firebase or doesn't take an account, I'll provide more than data on how to do it bellow.

Example of configuration:

            export const firebaseConfig = {   apiKey: "AIzaSwERfdilPYtcNDfvFR6x944EowerdfghfSDFsfg",   authDomain: "crud-456657.firebaseapp.com",   databaseURL: "https://crud-456657.firebaseio.com",   projectId: "crud-456657",   storageBucket: "crud-456657.appspot.com",   messagingSenderId: "10130122343423",   appId: "1:1013012342277:web:sd9f8sd8fs8dfs89df89s",   measurementId: "G-3FGJ34GFGJK" };          

How to go your firebase configuration.

Go to https://firebase.google.com/ and login with your account or create a new one.

Click on create a spider web app (This is the screen that you'll run across the offset time yous create a projects):

image

Or add a new project (If yous accept already other projects created):

image

Enter the name of your projection, have the terms, and end the other two steps on the wizard:

image

Next you'll meet something like this, from here you can catch the configuration key.

image

If yous missed the previous screen y'all tin can always get to the cog wheel on the left side panel, and click on project settings.

image

Now scroll downwardly to the Your App section and click on config radio button, and re-create the code highlighted on the image blare, and paste it on the firebase.ts file.

image

webpack banner

A simple simply powerful project to rapid prototyping and evolution of front-end apps, with scss (optional), pug (optional), ES7, webpack (bundlefy, uglyfy, etc). Very useful to create static websites or apps, without having to worry about setting upwardly the surroundings.

You can get the source code gratuitous on Github.

Features.

  • Modern Technologies: Full support for HTML5, PUG, JavaScript (Vanilla and ES7) and CSS (Sass, scss and PostCSS).
  • Built-in Server: Local development server with alive reloading.
  • Performance Tuning: CSS and JavaScript transpilation, bundling, autoprefixing, and minification.
  • Image Optimization: Optimizes images for loading speed.
  • Favicon Generation: Automatically generates all favicons for Spider web, Apple and Android devices from i image file.
  • Code Linting: Full support for JavaScript (ESLint) and CSS (StyleLint) linting.
  • Setup Wizard: Optionally install helpful libraries and snippets .including:
    • jQuery.
    • Google Analytics.
    • FTP deployment process.
  • Cutting Edge: Uses Webpack for processing and bundling your lawmaking.
  • Deployment: Built-in support for deployment via FTP.

Requirements.

  • Node.js (adult with node 12).

Installation Steps.

Clone repo:

                          git clone https://github.com/jomendez/simple-webpack-boilerplate &&  cd uncomplicated-webpack-boilerplate &&  rm -rf .git && git init          
  1. Run npm install.
  2. So run npm run setup to configure the app (include JQuery, etc).

In this step you'll be able to setup your google analytics, enable jquery, setup (optional) an FTP for deployments.

image

  1. Run npm run dev to open a browser and dejeuner a local spider web server with live-reload.
  2. Run npm run build build for production (./dist folder).
  3. Run npm run deploy to deploy your code to your FTP.

If everything went well (npm run dev)...

You lot browser should open a new tab and y'all should see something similar this:

image

Quick case.

It is recommended to create a new page within the src folder or employ the one that comes with the example page.pug to start adding your content.

image

So you tin can go to src/js/app.js file and add the following lines:

            const page = crave("../folio.pug"); document.querySelector('container').innerHTML = folio();          

The code above is going to transpile the pug file this item case (but information technology tin can be an html file).
So nosotros volition insert the content of the folio into the container tag on the index.html.

jose mendez portfolio

Virtually the author

I describe myself every bit a passionate Front-end developer, focusing on create, exam, and optimize total web apps with compelling user interfaces that runs in web browsers on whatsoever device, from desktop reckoner to tablets and cellphones, therefore, my principal allies are javascript, html, css, and the browser'southward issue loop. That'southward why you will always find me learning and improving my skills to main those pillars and it's surrounding frameworks and technologies, such equally angular, nodejs, ionic, react, etc.

Goals

Some times I find it a fiddling bit hard to interpolate/transmit the description above to recruiters and hiring managers, just with my online presence (before any interview or conversation). That's why my intention is that they just get information technology by seeing and interacting with this portfolio.

Thus I decided to create a portfolio/profile/interactive resume as a complement for my actual resume and Linkedin contour, in improver to that, also for this two reasons:

  1. To challenge my skills with css animations and interaction.

  2. To create a showcase and challenge myself in a cool framework that I was recently immersing: Threejs which is used to create 3d environments, interactions, etc. on the spider web.

I wanted to do something different for this projection, and so I thought... why don't I create a 3d interactive version of myself. I did a research on the cyberspace and I institute this commodity, about how to create an interactive 3D character with Threejs, and I used it every bit a guide to create my own 3d interactive graphic symbol:

https://tympanus.net/codrops/2019/x/14/how-to-create-an-interactive-3d-character-with-three-js/

About the (portfolio/profile/interactive resume)

At present, the portfolio/profile/interactive resume tin can be cleaved down into two chief parts:

  1. The get to know the non-technical side of the person, the activities that he likes more (the 4 inner buttons) click on the buttons to know more than about the author and see the interactions and animations of the character...

jose mendez portfolio inner menus

  1. The more technical part, more than like a resume, showing the technical skills, places he worked, some of his recent work (games, Ionic starters, etc.), featured blog posts, certifications etc.That you can admission by clicking on the outer buttons, (placed in the corners)

Portfolio

You tin can navigate to the portfolio/contour/interactive resume here:

http://world wide web.jomendez.com/portfolio/

javascript is weird

I mean, javascript could be weird for developers that are just starting with the linguistic communication and generally for developers that comes from other languages similar C++ or C# for example.

There are certain areas of the linguistic communication that cam blow your mind 🤯🤯
In this article nosotros are going to meet 5 examples, and keep information technology simple withing the ~2 min reading time.

Numeric separators

Lets take for example the post-obit lawmaking:

            const number1 = 2_0_0_0; const number2 = 6_0_0_0;  console.log(number1 + number2);          

What you think the result is going to exist?

Y'all tin can copy and paste the code on a browser programmer panel or you can play with it yourself on codepen.

The effect is 8000, but why?

The thing is that the underscore (_) is a numeric separator for numeric literal. It is used to group digits to make long numbers more readable, for example:

1234567

1_234_567 <-- Therefore, information technology is more than readable with the separator.

More info in this article.

Some weird types.

Some other example is when y'all run the code typeof nil

            typeof cipher; // event object          

which incorrectly suggests that nada is an object (it isn't, it'due south a archaic value).

well in this case it is not just a weird thing, it is a bug in the linguistic communication that can't exist corrected because information technology will restriction other parts of the code.

At that place is a more deep explanation in this article.

Meanwhile...

                          typeof NaN;  // outcome number.          

Is it weird that NaN — "non a number" is actually a number or is just me? On the other hand, NaN is not equal to itself.

            panel.log(NaN === NaN); //evaluates false.          

Functions.

In javascript a function can self-invoke it cocky IIFE (Immediately Invoked Function Expression) , so yous can do declaration and execution on the same argument.

            (part() { console.log('hello'); })(); //brandish 'hullo'          

As far as I know this just be in javascript. Information technology is quite useful, can be used to avoid variable hoisting from within blocks, protect confronting polluting the global surroundings and simultaneously allow public access to methods while retaining privacy for variables defined inside the part.

You can learn more than on this article

Reset an array

And terminal simply non to the lowest degree, the most weird way of resetting an array, you can set the length holding to cero: arr.length = 0;.

            const arr = [1,2,3,iv,v,6]; console.log(arr); // displays [i, two, 3, 4, 5, half dozen]  arr.length = 0; console.log(arr); // displays []                      

I hope you similar it, and if you know any other weird thing specific of the javascript language please experience free to share information technology with us. 😉

javascript

javascript Proxy.

This a new characteristic introduced in the ES6 standard. The Proxy object is used to define custom beliefs for central operations (e.g. property lookup, consignment, enumeration, role invocation, etc).

The nuts.

There are three key terms we need to ascertain before we go on:

  • handler — the placeholder object which contains the trap(s).
  • traps — the method(due south) that provide property access.
  • target — object which the proxy virtualizes.

Hither is a list of available Traps.

  • use
  • construct
  • defineProperty
  • deleteProperty
  • become
  • getOwnPropertyDescriptor
  • getPrototypeOf
  • has
  • isExtensible
  • ownKeys
  • preventExtensions
  • set up
  • setPrototypeOf

The list going on and on...

The syntax

            let proxy = new Proxy( target, trapObject );                      

Quick case.

Permit's see a quick case before we swoop in into create our array query library.

                          class Student {     constructor(first, last, scores) {         this.firstName = commencement;         this.lastName = last;         this.testScores = scores;     }     go average() {         permit boilerplate = this.testScores.reduce(              (a,b) => a + b,              0          ) / this.testScores.length;         return average;     } }  //instantiate the educatee class   allow john = new Student( 'John', 'Doe', [seventy, 80, 90] );  let johnProxy = new Proxy( john, {    //nosotros trap the go and print the holding accessed      get: function( target, key, context ) {         panel.log( `john[${key}] was accessed.` );         return john[key];     }  });  johnProxy.firstName; //output. //> john[firstName] was accessed. //> <property content>                      

In this example we are just intercepting the properties called, for example johnProxy.firstName and printed it to the console, this could be used for debugging purpose in dev environments. We can practice the same and intersect the 'set' and impress a message to the console when we prepare the value on a holding.

Let'due south create our query library.

It would be similar to write an assertion library, where yous can use the name of the field you want to query withing the method's call instead of passing it as a parameter.

Kickoff let's create the assertion object.

Here we are going to define the assertion operations, our proxy object will return the objects based on this conditions:

            allow assertions = {   Equals: (object, value) => object === value,   IsNull: (object, value) => object === nix,   IsUndefined: (object, value) => object === undefined,   IsEmpty: (object, value) => object.length === 0,   Includes: (object, value) => object.includes(value),   IsLowerThan: (object, value) => object < value,   IsGreaterThan: (object, value) => object > value,   EndsWith: (object, value) => object.endsWith(value),   StartsWith: (object, value) => object.startsWith(value), }                      

The proxy object.

Here we going to trap the become, of the target object to read the name of the property and make sure it starts with findWhere then nosotros use the object field name nosotros want to query, then the exclamation (from the assertions above), So the syntax volition looks something like this arr.findWhereNameStartsWith('Jo')

            allow wrap = arr => {   const prefix = 'findWhere';   let assertionNames = Object.keys(assertions);   return new Proxy(arr, {     get(target, propKey) {       if (propKey in target) render target[propKey];       var assertionName = assertionNames.notice(exclamation =>         propKey.endsWith(exclamation));       if (propKey.startsWith(prefix)) {         var field = propKey.substring(prefix.length,           propKey.length - assertionName.length).toLowerCase();          var assertion = assertions[assertionName];         return value => {           return target.filter(item => exclamation(item[field], value));         }       }     }   }) }                      

Declare the object.

Next step is to declare the object and wrap information technology up with the proxy.

            allow arr = wrap([   { proper name: 'John', age: 23, skills: ['mongodb', 'javascript'] },   { name: 'Lily', age: 20, skills: ['redis'] },   { name: 'Iris', age: 43, skills: ['python', 'javascript'] } ]);                      

Calling the methods

            console.log(arr.findWhereNameEquals('Lily')) // finds Lily. console.log(arr.findWhereSkillsIncludes('javascript')) // finds Iris.                      

The code above the first line will render the object where Property Proper noun is equal to Lily and impress it to the console, and the 2d line volition render the object(s) where skills holding includes javascript within the array.

Full source code.

Use the post-obit lawmaking to play more with javascript proxy.

Things to notice.

Notice how we phone call the a method in the assortment that nosotros didn't declared before arr.findWhereAgeIsLowerThan(30) nosotros use the proxy to read this method, the expected syntax is findWhere + <array_field_name> + <assertion> this allow u.s.a. to create custom queries using the array field proper noun we want to query within the method name:

  • arr.findWhereAgeIsLowerThan(27);
  • arr.findWhereNameEquals('Lily');
  • arr.findWhereSkillsIncludes('javascript');

Wrapping upwardly

With JavaScript proxy, you tin can wrap upwards an existing object and intercept any admission to its attributes or methods. Even if they don't be!

At that place are many real-world applications for Proxies:

  • Create SDK for an API.
  • validation.
  • value correction.
  • Revoke access to an object property/method.
  • Querying arrays with more readable methods (the main topic of this mail service).
  • belongings lookup extensions.
  • tracing property accesses.
  • Monitoring async functions.

Conclusions.

Javascript proxy enables a lot of possibilities to create more than readable APIs where y'all can combine field names, assertions and create dynamics methods on the fly, notwithstanding as you can encounter in the link below IE doesn't back up it and this can be a downside to create code that needs to be supported by all major browsers. Unfortunately, it'due south not possible to polyfill or transpile ES6 proxy code using tools such as Babel, because proxies have no ES5 equivalent.

For more info about javascript proxy and browser compatibility you tin can Larn more than here

native performance

Native operation

In this post we are going to cover how to accomplish almost native performance with APIs that the spider web provides, to make fast hybrid apps. Every twenty-four hour period the browsers evolves and improve at a very accelerated speed, and then in my personal opinion we are going to go to a signal were the performance of a spider web page running on a browser and the performance of a native applications is going to exist seamless, if nosotros are non there already.

What is a hybrid app

Hybrid applications are, websites packaged into a native wrapper (WebView). Basically, a hybrid app is a spider web app congenital using HTML5 and JavaScript, wrapped in a native container

Improving for the web

The goal of this article is to expose how to meliorate the HTML, CSS and javascript performance for mobile hybrid applications, is in deed to show some of the techniques used by the hybrid frameworks to boost the functioning on mobile applications

Rendering Performance

To write performant sites and apps you need to understand how HTML, JavaScript and CSS is handled past the browser, and ensure that the code you write (and the other third political party code y'all include) runs as efficiently as possible. Read more hither

requestAnimationFrame()

How information technology works:

  • When yous call requestAnimationFrame, it request that your role be called before side by side pigment
  • The role is chosen ~60 times/sec or throttled in the groundwork
  • Animations optimized into single reflow/repaint
  • Polish animations without jank

Example of requestAnimationFrame()

part animate() {    requestAnimationFrame(animate)    myElement.style.transform = `translateX(${x}px)`;    X++;  }  requestAnimationFrame(animate)          

requestAnimationFrame() Browser back up

requestAnimationFrame availability

Reference: https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

Avoiding Layout Thrashing with DOM batching

What is layout thrashing:

Layout Thrashing is where a web browser has to reflow or repaint a web page many times before the folio is 'loaded'. In the days before JavaScript'due south prevalence, websites were typically reflowed and painted only one time, simply these days it is increasingly common for JavaScript to run on page load which can cause modifications to the DOM and therefore extra reflows or repaints. Depending on the number of reflows and the complexity of the web page, there is potential to cause significant delay when loading the page, especially on lower powered devices such as mobile phones or tablets.

Reference: https://blog.idrsolutions.com/2014/08/beware-javascript-layout-thrashing/

This can be avoided by batching the writes and reads with fastdom (it relies on requestAnimationFrame())

How it works?

FastDom works as a regulatory layer betwixt your app/library and the DOM. By batching DOM access we avert unnecessary document reflows and dramatically speed up layout functioning.

More info here

fastdom example for native performance

Reference: https://developers.google.com/web/fundamentals/performance/rendering/avert-large-complex-layouts-and-layout-thrashing

ionappfullplus - promo-banner

Efficient style modifications

Skip layout and paint past only modifying composite-only
properties.

Modern browsers can animate 4 things really cheaply: position, calibration, rotation and opacity. If you lot animate anything else, it's at your own take a chance, and the chances are you're non going to hit a silky polish 60fps.

html cheap operations

Reference: https://www.html5rocks.com/en/tutorials/speed/high-performance-animations/

Passive Outcome Listeners

Indicate impact events won't cake scrolling, Run event listener without holding up scrolling, provides polish bear on and curl animations and gestures

Example:

passive event listener

Passive Outcome Listeners browser availability

passive event listeners availability

Reference: https://developers.google.com/web/updates/2016/06/passive-outcome-listeners

will-change

Indicates to the browser certain properties will change
frequently (ex: scrolling, animations, gestures, etc.)

Browser promotes element to it's own layer, smoother animations with less CPU usage (though
maybe higher RAM usage).

Note: Use with caution: If everything is optimized, goose egg is

will-change example:

will-change: auto; will-change: scroll-possition; volition-change: contents; will-modify: transform; will-change: opacity; will-change: left, top;          

Fallback:

transform: translateX(0)          

volition-change - availability

will-change availability

Reference: https://developer.mozilla.org/en/docs/Web/CSS/will-change

CSS containment

The new CSS Containment property lets developers limit the scope of the browser'south styles, layout and paint work. learn more than here

In other words, it point isolated elements, browser optimizes, limiting recalculation paint/layout/size/style to sub-tree, deriving in fast component updates

Example of CSS containment

containment example

css containment example speed

This layout is 1425x faster!

CSS containment browser availability

css containment availability

Reference: https://developers.google.com/web/updates/2016/06/css-containment

Conclusions

We highly recommend you to use a framework, frameworks do this stuff for y'all, for case in ionic all the components are optimized with these performance improvements.
In other words if you want to create a hybrid a mobile application endeavor to avoid direct DOM manipulation, ever use a framework, with that you'll exist more shut to accomplish native functioning .

ionic hacks

I've been working with ionic for a while at present, and I decided to make a compilation of useful ionic hacks, tips, tricks or simply useful information from my journey, so I tin accept a centralized place where I tin find easy and fast this useful compilation, and also share it with all the ionic developers, I promise this might be of some help for others.

I divided information technology into 3 categories (for now), I remember this is going to be an on-going process of keeping calculation ionic hacks, Every time I observe something interesting I'll update this postal service.

Ionic hacks index

- UI/UX

  • Hide Scrollbar when using Chrome
  • Configure your Ionic App Config
  • Making Text Selectable

- Debugging

  • Remote Debug on Android and iOS
  • Debugging faster on iOS & Android with -livereload
  • Targeting Platforms and Operating Systems
  • Target platform from url

- Practical solutions

  • ngZone, include into athwart cycle digest
  • Declare globally window's var for plugins with no wrappers
  • @ViewChild only works when the view is loaded
  • Utilize Crosswalk for Android
  • Improving Loading Times and performance of your Ionic App
  • Using Custom Scripts
  • Add cordova-android-support-gradle-release to resolve gradle version conflict issues (Android)

Lets go started

Hide Scrollbar when using Chrome

When debugging your ionic app, using for example ionic serve lab on Chrome, I affair that is actually annoying is the visible scrollbar:
chrome hide scroll bar

Go to app/apps.css to add the following css globally (this volition hibernate all the scrollbars inside your application):

* ::-webkit-scrollbar {   brandish: none; }          

Configure your ionic app config

We can alter the general behavior of components through the root configuration of our app. The Config lets you configure your entire app or specific platforms. You tin can set the tab placement, icon mode, animations, define dorsum button icon, and more. This is i of the most interesting ionic hacks.

@NgModule({   declarations: [ MyApp ],   imports: [     BrowserModule,     IonicModule.forRoot(MyApp, {       backButtonText: 'Become Back',       iconMode: 'ios',       modalEnter: 'modal-slide-in',       modalLeave: 'modal-slide-out',       tabsPlacement: 'lesser',       pageTransition: 'ios-transition'     }, {}   )],   bootstrap: [IonicApp],   entryComponents: [ MyApp ],   providers: [] })          

Yous could also configure these values at a component level

<ion-tabs tabsPlacement="peak">   <ion-tab tabTitle="Nuance" tabIcon="pulse" [root]="tabRoot"></ion-tab> </ion-tabs>          

Any value can be added to config, and looked up at a later in whatsoever component.

config.set('ios', 'favoriteColor', 'greenish');  // from any page in your app: config.get('favoriteColor'); // 'green' when iOS          

Making Text Selectable

You might have noticed that you can't select the text inside your ionic app, which is specially challenging if y'all want to enable the user to be able to select text (to exist able to re-create/paste for example) within of your awarding.

Y'all can utilize this css rule to all the awarding, or just to a specific element container:

torso {     -webkit-user-select: text;     user-select: text; }          

Remote Debug on Android and iOS

Android

For this yous'll need to have Android Studio installed on your computer

Connect your device to the computer and make sure it is correctly detected, by running adb devices (Android SDK is required).

Build your app and install it on your device past running ionic cordova run android --device command. In one case your app is launched on the device, open the Chrome browser on your estimator, in a new tab's url bar type: chrome://inspect/#devices, and inspect your device.

ionic device remote debug

iOS

Plug in your device and make sure it is correctly detected past your computer. Build your app and install it on your device by running ionic run ios --device.

Once your app is launched on device, open Safari dev tools (on your computer) by clicking on Develop > Your iPhone > Your app:

ios safari remote debugging

Debugging faster on iOS & Android with -livereload

This is very elementary, when you run the command to deploy to your device, add parameter -fifty ionic cordova run android --device -l y'all can also add parameter -c to display console logs in your control prompt:

--livereload, -l Spin up server to live-reload www files
--consolelogs, -c Print out console logs to terminal

Targeting Platforms and Operating Systems

Some times nosotros demand to notice in which platform the code is running, some scenarios are when y'all are using cordova plugins that are only supported past for example Android and iOS, and y'all are planning to deploy your app also to Windows app store, and every bit a PWA. A specific plugin with this characteristics is the admob complimentary plugin.

ionic-platform

Here is a list of the platforms supported:

ionic platforms

Target platform from url

This is a useful functionality, when yous run your application in the browser ionic serve yous can apply the --lab parameter to open your app into an iframe wrapper that call for specific platform, in that way is easy for you to visually select what platform target you want the ionic awarding to run.

Only what happen when you lot deploy your application to firebase hosting for example, maybe to demo a prototype for your clients, or in our instance to demo our latest starter on the ionic marketplace

In our case wecalled the application with the following parameters: http://< path to your app >?production=true&ionicplatform=android

For Android:
https://www.jomendez.com/ionappfullplus/?product=true&ionicplatform=android

For iOS:
https://world wide web.jomendez.com/ionappfullplus/?production=truthful&ionicplatform=ios

ngZone, include into angular cycle digest

As the official angular documentation states:

The most common use of this service is to optimize performance when starting a work consisting of 1 or more asynchronous tasks that don't require UI updates or error handling to exist handled by Angular. Such tasks can be kicked off via runOutsideAngular and if needed, these tasks tin reenter the Athwart zone via run.

In other words, it allows you to either execute code exterior angular bike digest (to improve performance) or, to include code executed asynchronous (exterior angular) inside the angular cycle digest.

A applied example is when we created the dialogFlow (chatbot) showcase, since the cordova plugin didn't accept the ionic wrapper, it executes the code outside of athwart:

            this.ngZone.run(() => {         panel.log(response);         let text = this.processCommand(response.result.fulfillment.speech);         this.messages.push({           text: text,           sender: "api"         });         this.content.scrollToBottom(400);       });          

ionappfullplus - promo-banner

Declare globally window's var for plugins with no wrappers

This is the same scenario as before, we needed to call the dialogflow plugin's api via window variable window.ApiAIPlugin if endeavor to call ApiAIPlugin from the window variable, Typescript will complaint nigh ApiAIPlugin non been a property of window

We accept 3 solution for this, one is what the title of this category suggest, declare the window variable globally:

import { DatabaseProvider } from "../../../providers/database/database";  declare var window;  @IonicPage() @Component({   selector: 'folio-dialogflow-chat',   templateUrl: 'dialogflow-chat.html', }) export grade DialogflowChatPage { //... }          

Second is to cast the window variable to "any" blazon

(<any>window).ApiAIPlugin          

And the third ane is to call the holding using the arry call format:

window["ApiAIPlugin"].requestText          

@ViewChild just works when the view is loaded

I remember faced this event before, but the last fourth dimension I did was crating the signature-pad showcase where I needed to reference a canvas within the HTML, and call the method clear() equally soon equally the page is loaded.

In one case you declare the @ViewChild() if you endeavor to use the reference on the constructor method yous'll go an fault:

Uncaught TypeError: Cannot read property 'clear' of cipher

One potencial solution is to call information technology when ionViewDidEnter lifecycle issue is called:

            ionViewDidEnter() {     this.signaturePad.clear();  }          

Apply Crosswalk for Android

Every Android version runs a dissimilar WebView (a browser that runs your ionic application). The performance is different across devices, and information technology tin can exist really bad on the former Android devices. To go a consistent performance and experience with fluidity and responsiveness on every Android device, you lot can install Crosswalk. Information technology basically embeds the latest Chromium browser into your awarding, it will add around 20Mb per APK, both ARM and X86.

To install the plugin you can run the following command:


ionic plugin add cordova-plugin-crosswalk-webview

Note:

Knowing this was very useful, when created our multi-platform Gamefy (which is a packet of five games in ane), because the functioning of the games was poor on android low-end devices, and crosswalk fixed the effect.

Improving Loading Times and functioning of your Ionic App

As every programmer should know y'all are first of all responsible for writing expert code that performs. Information technology's not the error of Ionic (almost of the time) if the app loads slowly, but there are few thinks you can do to improve your performance.

Make sure to use lazy load for your page, although when you generate a page from the ionic CLI it generate the folio prepare for lazy loading, the starters templates doesn't use lazy load.

By doing this, your app won't load all the pages on startup immediately but rather prolong the loading a bit so the first page will announced a lot faster. This is very important if you are creating PWA, this is 1 of the central points for PWA.

To learn more virtually how to utilise lazy load on an Ionic app, visit here

Every bit mentioned before, another improve is to use ngZone to execute tasks that don't require UI updates or error handling to be handled by Angular to improve performance.

Equally mentioned in the previous point, install crosswall can exist a boost in your performance particularly for low-stop android devices.

Finally, what can make a huge modify for all Ionic apps is edifice for production. This volition remove any debugging plugin, minify, uglify the code, etc. Simply run:


ionic cordova build ios --prod --release

That command volition activate Angular's production mode, and run a total product build so y'all can get the smallest bundle possible.
It will take a while, especially the first fourth dimension you run it, but information technology is worth it.

Using Custom Scripts

You'll notice that in the package.json file of your projection there are a belongings chosen scripts

"scripts": {
"clean": "ionic-app-scripts make clean",
"build": "ionic-app-scripts build",
"lint": "ionic-app-scripts lint",
"ionic:build": "ionic-app-scripts build",
"ionic:serve": "ionic-app-scripts serve",
}

Hither you can define your ain tasks, for deployment, android app signing, zipalign, etc. So every time you need to sign your apk to deploy to the app store, you can define a task to practice that

"scripts": {
"clean": "ionic-app-scripts clean",
"build": "ionic-app-scripts build",
"lint": "ionic-app-scripts lint",
"ionic:build": "ionic-app-scripts build",
"ionic:serve": "ionic-app-scripts serve",
"jarsign": "jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore release-key.jks path\\platforms\\android\\app\\build\\outputs\\apk\\release\\app-release-unsigned.apk jomendez",
"zipalign": "\"C:\\Users\\user\\AppData\\Local\\Android\\sdk\\build-tools\\27.0.3\\zipalign\" -f -5 iv path\\platforms\\android\\app\\build\\outputs\\apk\\release\\app-release-unsigned.apk path\\platforms\\android\\app\\build\\outputs\\apk\\release\\name.apk",

}

And then yous merely have to run:


npm run jarsign
or
npm run zipalign

Add cordova-android-support-gradle-release to resolve gradle version conflict problems (Android)

In my experience sometimes cordova plugins throw errors regarding packages versions vs environs versions, or the near common for me has been disharmonize between two or more cordova plugin, the most recent was when I was trying to integrate the barcodescanner plugin on ionAppFullPlus together with the facebook plugin.

I received the post-obit mistake:

Build fails with error
> java.lang.RuntimeException: coffee.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

The problem was that the ii plugin uses different versions for the supporting libraries

After few hours trying everything I found this plugin for Android (cordova-android-support-gradle-release) that aligns various versions of the Android Support libraries specified by other plugins to a specific version, which fixed the issue.

Installation:

cordova plugin add cordova-android-support-gradle-release

Conclutions

I volition try to update this post often with new ionic hacks, I call back in that location is a lot of things that can be washed to to meliorate the operation of ionic applications, or the developer's productivity, etc.

menu banner

With ionic CLI you can rapidly and easy create a Side Carte du jour app just by running the control

ionic start sidemenu          

or create a tab application by running:

ionic beginning tab          

Those are common navigation patterns used by a lot of mobile applications today:

In this brusk tutorial we are going to endeavor to combine those different navigation patterns into one application.

Nosotros volition proceed things simple, we are going to make the transition from a login folio (Taken from ionappFull4Pro starter) to our inside navigation, which combines side carte and tabs.

Login workflow

This is a module that is part of the ionappFull4Pro starter, and with information technology you'll be able to:
- Login with Firebase username and countersign
- Login with Google (native) //for this the app must run on a device or an emulator
- Login with Facebook (native) //for this the app must run on a device or an emulator
- Login with Google (PWA mode) //this mean that you lot tin can login with google running the app on the browser
- Recover your password
- Register new user
- User editable profile

Prerequisites

We assume you are familiar with ionic, and y'all have set up your ionic environment, if non you tin can follow this tutorial: https://ionicframework.com/getting-started#cli

We are going to start creating a blank ionic template using the CLI commandand so we are going to create all the needed pages:

ionic first convinedNavigation blank ionic g folio menu ionic g page tabs ionic yard folio tab1 ionic chiliad page tab2          

Spoiler warning

We are going to employ lazy loading, for load our pages, and so subsequently create the new project feel free to remove the home page generated by default.

Now use your favorite IDE to open the project (mine is Microsoft Code) and alter the rootPage variable to a cord "LoginPwaPage", this will tells ionic LoginPwaPage is the entry betoken page.

ionic app component

Lest import the login component from ionappFull4Pro into our project. First, copy the login-workflow binder (which contains login, profile,recover and register pages) into our project (also you tin can follow the instructions on the instructions.txt file included in the binder).

import login from ionappfull4pro

This is how it should looks like:

login workflow in our local project

Follow the instructions on the instructions.txt file to complete the import of this component:

Instructions.txt

Instructions to import this component in your existing ionic app.  If yous don't have an ionic app created, create ane, by running the post-obit control on the command console, on the folder you want your app to exist created,  once your app is created locate the pages folder and copy this component (binder) in the folio folder:  $ ionic start MyAppName blank  for more info go to the ionic official documentation.   Once yous have your app created Install the components dependencies (see what is imported on the ts files on this component):  On your firebase dashboard enable the electronic mail/countersign methods, encounter documentation: http://jomendez.com/ionAppFull4Pro-documentation/#!/firebase_configuration 	 Notes: For this component to piece of work you need to setup firebase and also import the DatabaseProvider from "/providers/database/database" included on the ionAppFull4Pro project. Besides import /providers/auth-information provided from ionAppFull4Pro to your app As well copy src/config/config.ts from this project (ionAppFull4Pro) to your application, and enter your firebase information.          

Remember to install the firebase dependencies and add the providers to the app.module.ts file:

npm i --save angularfire2 firebase          

For this tutorial we are going to use the login-pwa component to keep information technology simple and be able to test the app in the browser without having to run it on a device or emulator. Login pwa component uses some "fancy" blitheness library chosen VegasJs (this is not required for the login component to work, y'all can easily remove it). In lodge to include it and brand it work you lot'll need to re-create few thinks from ionappFull4Pro starter, showtime include the jquery library and vegas dependencies on alphabetize.thml and so re-create the files into avails binder:

add jquery and vega index
images on the assets folder

This is how the app.modules should looks like afterward all the imports and declaration:

app modules dependencies

One concluding thing information technology we have to redirect to menu page later on login, and then we will have to modify the login() method, lets comment the code that redirects to the profile folio and add the lawmaking that ready the MenuPage equally the root:

redirect to menupage

Build the menu navigation:

Add together this carte lawmaking to your src/pages/menu/card.html

              <ion-menu [content]="content">   <ion-header>     <ion-toolbar>       <ion-championship>Menu</ion-title>     </ion-toolbar>   </ion-header>     <ion-content>     <ion-list>       <button ion-item menuClose *ngFor="allow p of pages" (click)="openPage(p)">           <ion-icon detail-start [proper noun]="p.icon" [color]="isActive(p)"></ion-icon>           {{ p.championship }}         </button>     </ion-list>   </ion-content> </ion-carte>   <!-- master navigation --> <ion-nav [root]="rootPage" #content swipeBackEnabled="imitation"></ion-nav>          

Add this lawmaking to src/pages/bill of fare/carte.ts
Notice that in folio i of the pages that can be called is the Contour page that comes with the login component from ionappFull4Pro starter

            pages = [     { title: 'Tab 1', pageName: 'TabsPage', tabComponent: 'Tab1Page', index: 0, icon: 'home' },     { title: 'Tab 2', pageName: 'TabsPage', tabComponent: 'Tab2Page', alphabetize: ane, icon: 'shuffle' },     { title: 'Profile', pageName: 'AfterLoginPage', icon: 'contacts' },,//notice we cal here the Profile that comes with the login workflow component on ionAppFull4Pro starter   ];          
import { Tab2Page } from './../tab2/tab2'; import { Tab1Page } from './../tab1/tab1'; import { TabsPage } from './../tabs/tabs'; import { Component, ViewChild } from '@athwart/core'; import { IonicPage, NavController, Nav } from 'ionic-angular';    @IonicPage() @Component({   selector: 'page-menu',   templateUrl: 'menu.html', }) export class MenuPage {   // Basic root for our content view   rootPage = 'TabsPage';     // Reference to the app'southward root nav   @ViewChild(Nav) nav: Nav;     pages = [     { title: 'Tab ane', pageName: 'TabsPage', tabComponent: 'Tab1Page', index: 0, icon: 'home' },     { title: 'Tab 2', pageName: 'TabsPage', tabComponent: 'Tab2Page', index: 1, icon: 'shuffle' },     { title: 'Profile', pageName: 'AfterLoginPage', icon: 'contacts' },   ];    constructor(public navCtrl: NavController) { }     openPage(page) {     let params = {};       // The index is equal to the order of our tabs inside tabs.ts     if (folio.index) {       params = { tabIndex: folio.index };     }       // The active child nav is our Tabs Navigation     if (this.nav.getActiveChildNav() && folio.index != undefined) {       this.nav.getActiveChildNav().select(page.index);     } else {       // Tabs are not agile, so reset the root page        // In this case: moving to or from SpecialPage       this.nav.setRoot(page.pageName, params);     }   }     isActive(page) {          let childNav = this.nav.getActiveChildNav();       if (childNav) {       if (childNav.getSelected() && childNav.getSelected().root === page.tabComponent) {         render 'chief';       }       return;     }       // Fallback needed when there is no active childnav (tabs not active)     if (this.nav.getActive() && this.nav.getActive().name === page.pageName) {       return 'primary';     }     render;   }   }          

Adding the Tab

Open your src/pages/tabs/tabs.html and change it to:

<ion-tabs [selectedIndex]="myIndex">   <ion-tab [root]="tab1Root" tabTitle="Tab ane" tabIcon="dwelling"></ion-tab>   <ion-tab [root]="tab2Root" tabTitle="Tab 2" tabIcon="contacts"></ion-tab> </ion-tabs>          

This tab bar will exist pointing to the 2 tabs pages we created at the commencement.
Now change your src/pages/tabs/tabs.ts

import { Component } from '@athwart/cadre'; import { IonicPage, NavController, NavParams } from 'ionic-angular';   @IonicPage() @Component({   selector: 'page-tabs',   templateUrl: 'tabs.html', }) export class TabsPage {     tab1Root: whatever = 'Tab1Page';   tab2Root: whatsoever = 'Tab2Page';   myIndex: number;     constructor(navParams: NavParams) {     // Set the active tab based on the passed index from menu.ts     this.myIndex = navParams.data.tabIndex || 0;   } }          

Now we only need to add together a menu button to all of our pages and then nosotros can toggle the menu from everywhere. Become through these ii files (tab1, tab2) and change it, add together the following html lawmaking:

Tab1

<ion-header>   <ion-navbar>       <button ion-push button menuToggle>       <ion-icon name="menu"></ion-icon>     </button>     <ion-championship>Tab1</ion-title>   </ion-navbar> </ion-header>   <ion-content padding>   This is tab 1 content </ion-content>          

Tab2

<ion-header>   <ion-navbar>       <button ion-button menuToggle>       <ion-icon name="carte du jour"></ion-icon>     </push>     <ion-title>Tab2</ion-title>   </ion-navbar> </ion-header>   <ion-content padding>   This is tab two content </ion-content>          

This is the result:

Attempt it yourself:

Conclusions

With this article we got two navigation pattern working together, it could be a trivial flake catchy, simply it is possible, as well we were able to integrate/import the login module very easy, from the ionAppFull4Pro ionic starter into our applications, saving united states of america a lot of time and development try, and but with that nosotros were able to implement an app with firebase login, google login, recover password, register user, and profile page.

Cheers,
Jose

ashbyartiontily.blogspot.com

Source: http://www.jomendez.com/

0 Response to "Mongodb Ionic Cannot Read Property Protype of Undefined"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel