Friday, April 9, 2021

State Management techniques with Angular Framework

There are several ways of handling state in Angular

  • Using Angular Change Detection Strategy
  • Implement Rxjs library 
  • Using third party library like ngrx or angular redux
Change Detection Strategy :
Angular by default uses the change detection using @input and@output decorators through which state can be handled if components have parent child relationships.

But using default change detection the components checks those changes everytime if event or some thing changed in components. 

We come across many scenarios where we would like to do the change on condition basis which could improve the performance of an application. 

Angular Backendless Development using Json-server

While working on Fronend project if backend APIs are not ready, developers can still start working using JSON Server and create mockApis to start. 


There are different ways to achieve this useful feature.



We have already discussed Custom Http interceptor by HttpClientModule approach in a different post.

This post is about how can we use json-server to mock the real back end. We need to install json-server, so that we can use it. Run below command to install this globally in your system.
npm install -g json-server
I am assuming you already have angular environment ready.
At this point decide on the data structure you are expecting as a result of the service call. Create a JSON file with some mock data.
//mockData.json
{
  "users": [
    {
      "id": 22,
      "fName": "Sourav",
      "lName": "Ganguly"
    },
    {
      "id": 10,
      "fName": "Sachin",
      "lName": "Tendulkar"
    }
  ]
}
Now run below command and check
json-server mockData.json
http://localhost:3000  //you will see this url in console
Open above url in any browser and see you will be able to see "/users" under "Resources" section. The user data can be accessible via http://localhost:3000/users url.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class UserService {
    url = "http://localhost:3000/users";
    constructor(private http: HttpClient) {}
    getUser(): Observable<any>{
        return this.url.get(this.url + '?_sort=id')
                    .map(response => response.json());
    }
}
We can apply sort/ filters/ search on the response data. There are lot of other features, check json-server for more information.

To use this cool feature we need to install this dependency, some developers don't want to use additional dependency, otherwise this is another easy way to implement fakebackend in AngularJS.

Thanks for reading. Feedback and comments are always welcome!!!

Updating Angular Version

 Before updating any existing Angular Project, Please  verify below checklists

1.  Check the current version of the existing APP and compare the changes with the latest APP

From https://update.angular.io/?l=2&v=8.1-11.0 link

This will provide all the updates which needs to be done on existing project

2.  Try ng update command, this command will check the version of all the existing plugins and will give suggestions of some of the plugins to update.

3. Open package.json and update all the suggested versions to be updated.

4. Make sure to update all the existing thirdparty plugins and check all there compatibility with the latest version and update those as well.

It is recommended to always use the Licenced packages and plugins to be used.

5. Run  npm install command to update all the packages and plugins

There are certain warnings which will be notified at the time of updates.

Kindly check those warnings and fix as suggested.

Make sure to delete node_modules and package_lock.json files before installing new versions.

6. Create all the checklists of the modules and components on which the changes are required and have impact on the project.

For example:

Renderer class is deprecated from Angular9.

Some for IE-10,11 and IE mobile is removed

7. Update the existing documents and start using the latest version progressively or gracefully without having less impact on project deliveries and performance.

 

Wednesday, May 11, 2016

Difference Between Constant and Value in AngularJS

Today I was reading AngularJs documentation about Constants and Values.

As far as I understand, I would like to put together all the reading which I gathered.

1. Constant can be used during config phase of Angular Js and Value is can only be used during run phase.

2. A constant can be injected anywhere as its value cannot be changed that is why it cannot be intercepted by a decorator 

For eg:

var app = angular.module('app', []);

app.constant('PI', 3.14159265359);

app.controller('appCtrl', function(PI) {
    var radius = 4;
    // calculate area of the circle
    var area = PI * radius * radius; 
});
A value cannot be injected into configurations, But it can be intercepted by a decorator.

var app = angular.module('app', []);

app.value('greeting', 'Hello');

app.config(function ($provide) {
    $provide.decorator('greeting', function ($delegate) {
        return $delegate + ' World!';
    });
});

You can learn more about decorators in below blog:
http://www.bennadel.com/blog/2870-using-module-decorator-in-angularjs-1-4.htm


3. Objects can be used inside a constant as long as we have not decide to change any value therein.
So, it is best to stick with values if values are changeable.

// Storing multiple constant values inside of an object
// Keep in mind the values in the object mean they can be modified
// Which makes no sense for a constant, use wisely if you do this
var app = angular.module(‘myApp’, []);

app.constant(‘config’, {
    appName: ‘My App’,
    appVersion: 2.0,
    apiUrl: ‘http://www.google.com?api’
});
// Storing multiple values inside of an object
var app = angular.module(‘myApp’, []);

app.value(‘user’, {
    firstName: ’‘,
    lastName: ’‘,
    email: ’’
});

Monday, May 9, 2016

How to improve Angularjs Performance

If  you are planning to create a large application using Angularjs, you need to take care of some basic performance issues in angular which may slow down your application.

1. Minimize Watchers

Angularjs uses dirty checking to keep track of all the updates in an app.So if we use so many watchers in our app it will rerun the digest cycle if one watcher is dependent on other watcher.

The following codes creates so many watchers.

1. Avoid using {{expressions}} instead use ng-bind.
2. Instead of using ng-repeat='product in products' use ng-repeat = 'product in products trackby product.id', also you can add pagination or autoscroll if using ng-repeat.
3. Avoid using $scope.$watch instead use $watchcollection
4. Avoid {{ value | filter }}, instead use $filter inside controller.
5. Use ng-if instead of ng-show.
6. If lot of changes happen in ng-model , Debounce it like ng-model-options="{debounce: 250}"
7. Use bind once if possible like below:
{{name}} to {{::name}}
8. Avoid calling $scope.apply and $scope.digest manually, as angularjs automatically calls these process.

If we put  :: before value data will work as a one way binding.


Thursday, May 5, 2016

Integrating IIS Express with asp.net and connecting to DB

Yesterday I installed asp.net application on my system without installing visual studio and heavy editors.

Actually my purpose was to just run project and redesign the layout for responsive structure.
If you are comfortable with sublimeText or dreamweaver editor and would like to implement a static changes or frontend coding this article will be so helpful.

1. Install IIS Express from https://www.microsoft.com/en-us/download/details.aspx?id=48264 

2. Install SQL Server 2014 from https://www.microsoft.com/en-in/download/details.aspx?id=42299 and while installing remember/note username and password for database connectivity credentials

3. I had a backup file of SQL named sqlbackup.bak

To import .bak file in SQL Server follow below steps:
  • Connect to a server you want to store your DB.
  • Right-click Database.
  • Click Restore.
  • Choose the Device radio button under the source section.
  • Click Add.
  • Navigate to the path where your .bak file is stored, select it and click OK.
  • Enter the destination of your DB.
  • Enter the name by which you want to store your DB
4. After IIS Express is installed add your  asp.net files into Documents/My Websites/Website1/ folder
5. Open SQL Server 2014 Configuration Manager and Open
SQL Server Network Configuration -> Protocols for MSSQLServer : Enable Named Pipes and TCP/IP and restart sql server
6. Add connection string to web.config file.

Now after installing and configuring:
Open http://localhost:8080/myproject/ and done !!!

If you want to change css/html code can use any editor save and it just works great.







Wednesday, May 4, 2016

Services, Factories or Providers

When we start creating an angular js app, there are many modules and functions which doubts us which one to use and whereThe major ones are services, factories and providersThey both seems like so similar in angularjs and lets go ahead and work around some code examples which clearly mention the correct ways.

This shows how the CarService will always a produce a car with 4 cylinders, you can't change it for individual cars. Whereas CarFactory returns a function so you can do new CarFactory in your controller, passing in a number of cylinders specific to that car. You can't do new CarService because CarService is an object not a function.
The reason factories don't work like this:
app.factory('CarFactory', function(numCylinder) { this.dealer="Bad"; this.numCylinder = numCylinder
});

| Type | Singleton| Instantiable | Configurable|
| Factory | Yes | No | No |
| Service | Yes | Yes | No |
| Provider| Yes | Yes | Yes | ---------------------------------------------------

app.factory('CarFactory', function() {
function Car(numCylinder) {
this.delaer="Bad";
this.numCylinder = numCylinder
};
Car.prototype.breakCylinder = function() {
this.numCylinder -= 1;
};
return Car;
});
---------------------------------------------------
---------------------------------------------------
---------------------------------------------------
---------------------------------------------------
app.factory('CarFactory', function() {
return {
numCylinder: 4
};
});
app.service('CarService', function() {
this.numCylinder = 4;
});
And automatically return a function for you to instantiate, is because then you can't do this (add things to the prototype/etc):
See how it is literally a factory producing a car.
The conclusion from his blog is pretty good:
In conclusion,
  1. Use Factory when you need just a simple object such as a Hash, for example {foo;1, bar:2} It’s easy to code, but you cannot instantiate it.
  2. Use Service when you need to instantiate an object, i.e new Customer(), new Comment(), etc.
  3. Use Provider when you need to configure it. i.e. test url, QA url, production url.
If you find you're just returning an object in factory you should probably use service.
Don't do this:
Use service instead:

Wednesday, November 30, 2011

Use of various setting in php.ini file

What is php.ini  in php ?
php.ini is a configuration file in php than can be used to customize various setting in php. Easy way to customize the behavior of php.When PHP server starts it look for php.ini file to load various settings such as maximum file upload, error logs, short open tags, global variables, maximum execution time etc.

IF you want to do some custom configuration in php For eg. : in vertrigo server default maximum upload size is 2M if you want to change its size to 80M then through php.ini file you can change is size as below
upload_max_filesize =80M

Some errors if settings are not customized in php.ini file

1. Short Open tag :  
    code inside php.ini file : short_open_tag =On
    if short open tag is even off then the below code will print
                                                           <?php echo "short open tag is off"; ?>   
                                                           Output: short open tag is off
   but this below code will print

                                                          <? echo "short open tag is off"; ?>   
                                                          Output: <? echo "short open tag is off"; ?> 

   because php does not recognise this open tag as php tag so its is treated as a html content .

In order to use <?xml ?> inline we need to off short open tag

2.  Register Global Variable :
                                                It is suggested that register global variables must be always off in php.ini settings because it will inject your scripts with all sorts of variables, like request variables from HTML forms.
So for security reason register global must be always off.


Misuse of register global on:

<?php
if (isset($_SESSION['user'])) {

    echo 
"Hello <b>{$_SESSION['user']}</b>";

} else {

    echo 
"Hello <b>Guest</b><br />";
    echo 
"Would you like to login?";

}
?>


When register_globals = on, we could also use $user in our example above but again you must realize that $user could also come from other means, such as GET (through the URL).
if set 
$user=$_SESSION['user'] ; 
if register global is off this variable cannot be used globally. but its not secured either to use session within a variable coz this $user canbe set from other methods such as GET,POST etc by user.

To use global variables you can use the below script and add to beginning of every file or function.inc.php file and call it every time before start working with user variables.This will prevent problems with wrong initialized variables or users who try to break your application.
if (ini_get('register_globals')) {
    foreach (
$GLOBALS as $int_temp_name => $int_temp_value) {
        if (!
in_array($int_temp_name, array (
                
'GLOBALS',
                
'_FILES',
                
'_REQUEST',
                
'_COOKIE',
                
'_SERVER',
                
'_ENV',
                
'_SESSION',
                
ini_get('session.name'),
                
'int_temp_name',
                
'int_temp_value'
            
))) {
            unset (
$GLOBALS[$int_temp_name]);
        }
    }
}

3. Maximum Execution Time : This sets the maximum time in seconds a script is allowed to run before it is terminated by the parser.
Fatal error: Maximum execution time of 30 seconds exceeded in ......
If the site is not running in safe mode you can change the maximum execution time using the below function
set_time_limit()
else set it in php.ini file as below
max_execution_time =600