Http interceptor in AngularJS : adding tokens and loading image to every http request

While creating AngularJS applications,we might need to send multiple  http requests to backend apis to fetch the data that need to be populated within our HTML.In most cases, these backend apis might be protected using token .Also we might need to add a loading image to indicate the user that the data is being fetched. HttpInterceptor helps us to a display the loader image before and hide the loader image after completing the request  and also add token to every request header.This tutorial helps us to create an HttpInterceptor in AngulaJS. We create an  app using the following code

Now we create a factory which will intercept http requests.Inside the interceptor we use a variable httpRequestNumber,which tracks the number of requests.When a new request comes up we increment it httpRequestNumber++ and on response or error we decrement it httpRequestNumber– .We also inject $q and $rootScope.$q is service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.$rootScope is the root scope .every app has single root scope. All other scopes are descendant scopes of the root scope.We also add a token to the request header using the following code.

The interceptor factory will look like this….

Join two tables and get count in mysql:Example with hasMany relations in sequelize

Consider we have two tables ‘users‘ and ‘comments‘.Each user can have multiple comments so that ‘users‘ and ‘comments‘  have ‘hasMany‘ relation. The foreign key is user_id in the comments table. The structure of both tables are as follows Users id    | name |    email 1    userone    user1@gmail.com 2    usertwo    user2@gmail.com Comments id    | comment        | user_id 1      commentone      1 2      commenttwo      1 3      commentthree    2 4      commentfour     2 5      commentfive      2 6      commentfive      2 As you can see, the user with id 1 has two comments and the user with id 2 has  4 comments. To get all users with their respective number of comments, we can use the following query.

The result will be 1 userone user1@gmail.com 2 2 usertwo user2@gmail.com 4 Sequelize Example   To learn more about sequelize, see the following article https://truetocode.com/orm-using-sequelize-orm-with-express-node-js/418/ For our example, we need to create two model files usersModel.js

  commentsModel.js

  hasMany relation Now we need to define hasMany relations from users to comments, in your db.js file….

Angular JS 1.6 – server side pagination with sorting using Angular UI Bootstrap

Angular 1.6 SPA server side pagination of data with sort. To create a SPA which lists user data with pagination  and sorting we need the following CDN links – Angular JS 1.6.9 js CDN. – Angular JS UI bootstrap -Bootstrap components written in pure AngularJS . – Bootstrap CSS file. STEP 1 – Create file index.html and add the relevant CDN links using the following codes.

STEP 2 – CREATING ANGULAR MODULE and DEFINE THE APP create, register and retrieve Angular JS module using the following code.The name of the module is ‘userLog’.

and in the HTML.

STEP 3 – DEFINE THE CONTROLLER AngularJS applications are controlled by controllers. The ng-controller directive defines the application controller.The name of the controller here is ‘listController’.In HTML , add the following code

STEP -4 CREATING SERVICES AND INJECTING THEM In this example we will create two services one for getting the total number of users and other for getting the data each page.The name of the first service is ‘count’ and name of the second service is ‘getloglist’

Services in both cases send HTTP requests to the APIs.For this we inject $http service.The $http service get takes a single argument which…

Generator Functions in JavaScript : asynchronous behaviour of Javascript Part -3

For part 1 and part 2 of this series, see the following links https://truetocode.com/understanding-callbacks-and-callback-hell-in-javascript-asynchronous-behavior-of-javascript-part-1/697/ https://truetocode.com/understanding-promises-in-javascript-asynchronous-behavior-of-javascript-part-2/730/   JavaScript version ES6/ES2017, a new kind of function called generator functions was introduced. These special functions help you to manage asynchronous operations with more ease. Generator functions can be paused and then continued. Generator functions are declared with an asterisk (*) and have a yield keyword which yields data. See the following example to see the proper syntax for using Generator functions.

  There is a next method in the generator function prototype. To get the value of the first yield we use the next() method.

    Here you can see that the response object has a key-value which gives the value of the yield and a done key which represents the status. Here in our example,  value will be 1 and done will be false. We have two yields in the generator function .next() gives false two times and a third time gives done as true. If you add a return to the generator function next() will have key done as true.

        Now, if a return is done before a yield

Here you can see that the second yield…

Prototypes and Prototypal inheritance in Javascript

The word prototype means an early model or a primary version of a machine or a product.All further version created from that prototype will inherit the properties of that prototype.Prototype-based programming is a style of object-oriented programming in which behaviour reuse is performed via a process of reusing existing objects via delegation that serve as prototypes.(Wikipedia). Nearly all objects in JavaScript are instances of Object which sits on the top of a prototype chain.The Object.prototype is on the top of the prototype inheritance chain. That means almost all the objects in JavaScript inherit the properties and methods from Object.prototype.JavaScript Date objects inherit from Date.prototype. Array objects inherit from Array.prototype. Prototype determines the behaviour of a data object.Properties including methods are inherited from the prototype.See the below array which inherits prototypes from Array.prototype.You can see is array,map,reduce etc which are inherited from Array.prototype Prototypal inheritance In Javascript a function is a first-class Object.All JavaScript objects inherit properties and methods from a prototype.

In the example above, function Person() is called object constructor function.Wth the new keyword,we can create new objects fusing the constructor function.

both myGo and myGoGo has properties first,last,age,eyecolor and  prototype We cannot add a new property to an Person directly.we can add it to its prototype.

Difference between a Framework and a Library : Javascript point of view

While attending interviews for programming jobs,one of the most common question you would face is to explain the difference between a libarary and a framework.Here in this article we look at the difference between a library and a framework from a Javascript point of view. Library Libraries provide methods/functions/modules  that can be useful while building your application.While using a library the control is with your code and you call the functions the libraries provide from within  your code.These functions are reusable and can be used at different parts of building your application.There are many Javascript libraries like JQuery,JqueryUI,moment.js etc.These libraries provides functions that serves different purposes.   So we can generally describe the working of a library as We call the library functions from from our code Flow Control is with our code                For example when using JQuery library, we include the library in our code and call the library functions from within our code in the following way

Framework A framework provides structure,resources for building your application.While using a framework you call your logic from within the framework .The control is with the framework code , your code is called when  logic is…

first-child and nth-child selectors : Styling multiple Elements with same class – CSS
css , Beginner , Uncategorized / July 7, 2018

first-child  – This selector selects first child of its parent. To color first one of elements with the same class,we use first-child selector.Consider below example with multiple divs(.box)  inside parent div(.container).To change the style of first div

  nth-child – This selector selects nth child of its parent. We can achieve the above result using nth-child selector .The number in the bracket indicates the order of the child

 

How to change ‘sql_mode’ in mysql
PHP , Uncategorized / July 2, 2018

To see Mysql mode settings,do the following query. Mysql mode is not linked to any particular database. Modes can be set locally to the session (connection), or for the server globally.

This gives results like below   Now to change sql_mode,you need to run query like this

Example Some times after  importing database and changing some table structure,you may get an error like this. This is because NO_ZERO_IN_DATE and NO_ZERO_DATE is enabled in and database has invalid date values. NO_ZERO_IN_DATE The NO_ZERO_IN_DATE mode affects whether the server permits dates in which the year part is nonzero but the month or day part is 0. Example – ‘2010-00-01’ or ‘2010-01-00’ NO_ZERO_DATE This mode is deprecated This determines whether the server permits ‘0000-00-00’ . NO_ZERO_IN_DATE also depends on whether strict SQL mode is enabled. Removing above modes from sql_mode  lets the server allow invalid dates in the aforementioned format     Or to set it PERMANANTLY, change etc/my.cnf

and restart WHAT is sql_mode Server SQL modes determine what SQL syntax MySQL should support and what kind of data validation checks it should use. This makes it easier to use MySQL in different environments. See more on  list of sql…

Event propagation in javascript – Capturing and Bubbling

Event propagation is the propagation of an event through the elements in the HTML DOM. When an event happens phase1 – Event Capturing is done until the target is reached phase2 –  Bubbling is done executing handlers on the way Event bubbling and capturing are the two ways of event propagation in processing an event by the HTML DOM API.Event bubbling means that when an event happens, it propagates all the way up the parent to the ancestor elements. Bubbling When an event happens on an element,say click, it first runs the handlers on it, then on its parent, then all the way up.See the below example -The button inside the wh4 div was clicked. Onclick handler is on the ancestor wh4 is run.   Not every event get bubbled.Here is a list of  the most common event handlers. onAbort onBlur onChange onClick onDblClick onDragDrop onError onFocus onKeyDown onKeyPress onKeyUp onLoad onMouseDown onMouseMove onMouseOut onMouseOver onMouseUp onMove onReset onResize onSelect onSubmit onUnload Not every event bubbles.

If x is true then the event bubbles.You can check this creating the event By default all the Browsers support event bubbling. Event Capturing When an event happens capturing occurs in a way …

What are cookies and how to set and get them with Javascript

Cookies are data stored as text files in the computer.They are used store data that are needed to be remembered , like user information.Cookies can be set in client side and server side. For example,consider a user sign in to your website.The server sends back some response.The response have a token/id that can be stored as a cookie.This cookie value can keep the users details status in the client side. Cookie has a name and value pair,expiry time,path and secure . The security flags that are used to provide more security HttpOnly – HttpOnly flag sets the cookie unavailable to client side scripts.This prevent cross site scripting attacks(XSS) secure – Sets cookie to be send via a secure encrypted channel.Browser will send cookie only via an HTTPS request and prevent sending cookie via HTTP request. setcookievalue This function has three arguments name – cookie name. value – value of the cookie. hours- hours determine the expiry hours. document.cookie lets us store the cookie associated with the current document. getCookie This function has one argument ,cookie name document.cookie gets all the cookies associated with the current document.A cookie with a specific name can be obtained using the getCookie function.   getCookievalue This function has…

Share this page in social media platforms