Search

Logging in AngularJS Applications Made Simple

What comes to mind, when you think of a JavaScript framework that can be used to build applications across platforms, achieve maximum speed with accelerated performance and ensure quick builds? Just AngularJS, isn’t it?  Powered by Google, Angular was developed as a framework to give you a toolset for powering your single page application development, work well with other web-based libraries and be fully extensible. All its features can be modified and even replaced to give you complete freedom in developing your own unique workflow.  As a pure JavaScript framework, Angular can be added to an HTML page with a normal <script> tag with src attribute pointing to the source framework library. AngularJS extends HTML attributes using Directives.  It binds data to HTML using Expressions.  AngularJS can be downloaded from.  If you’re new to AngularJS, it is better to get introductory information from. This site provides the basic information required to start working with AngularJS.  It has various features including MVC Architecture, Directives, Expressions, Controllers, Filters, HTML DOM, Modules, Views, AJAX, Scopes, Services, Dependency Injection, Logging and Internationalization. We will deal with Logging in the following section. IntroductionAngularJS includes a logging service called $log, which logs the messages to the client browser's console. The $log service includes different methods to handle the log for error, information, warning or debug information. It can be useful in debugging and auditing. This article will help you learn about each type of log. The topics we will go through in this article are: Introduction to logging Testing AngularJS Logging Application What Is Application Logging? Angular Logging: The Improved Approach Logging with AngularJS - extending the built-in logger $log in AngularJS Turn off logging in AngularJS  Introduction to logging AngularJS has an impressive and robust logging mechanism in-built through the $logService and $log injection.  The $log service includes different methods to log the error, information, warning or debug information. It can be useful in debugging and auditing.  The main purpose of all AngularJS logging services is to simplify debugging and troubleshooting. To reveal the location of the calls to $log in the JavaScript console; you can "blackbox" the AngularJS source in your favorite browser. To blackbox in the browser, go to the page, right click it, “Inspect” it in developer mode, and then read the console. Note: All browsers do not support blackboxing. AngularJS logs everything to the console, which is neither a robust or scalable solution. Sometimes, you need to be able to intercept the exceptions and do something extra. This could be as simple as adding extra information or sending all logs to the server/database. $log in AngularJS AngularJS programmers frequently use console.log to record errors or other informational messages in their applications. Although this is fine while debugging your application, yet it is not a best practice for production environment. As AngularJS is all about services, it is a better idea to create a logging service that you can call from other services and components due to some event which needs to be logged. In this logging service, you can still call console.log, but you can also modify the service later to record messages to store them in local storage or a database table via the Web API. Some methods that we will use for logging in AngularJS $log are: log();  to write a log message info(); to write an information message warn(); to write a warning message error(); to write an error message debug(); to write a debug message  The above methods are used for different categorizations of $log. Testing AngularJS Logging Application An Example of logging in AngularJS is: Considering you have already downloaded the latest AngularJS file from (here we are using the minified version of AngularJS as angular.min.js). We can even use the AngularJS CDN for the same provided by Google: https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js <!DOCTYPE html> <html> <head> <title>Logging Example in AngularJS</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script> <script> var app = angular.module('myApp', []) app.controller("myController", function ($log) {             $log.log('This is log.');             $log.error('This is error.');             $log.info('This is info.');             $log.warn('This is warning.');             $log.debug('This is debugging.');         }); </script> </head> <body ng-app="myApp"> <form id="form1"> <div ng-controller="myController"> <p> <h1> Go to Inspect, through browser blackbox <br/> to see the Console for the different loggers.   </form> </body> </html>Now run the logging example as an HTML file and check the output, which will look like this: Go to Inspect, through browser blackbox to see the Console for the different loggers. In the Inspect Window, go to Console, and see the result as: This is log. This is error. (In red font displayed with error icon) This is info. This is warning. (In brown font with warning icon) Here is a more complex example, which logs according to events generated as follows: <!DOCTYPE html>  <html>  <head>  <title>Logging Example in AngularJS</title>  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>  <script>  var app = angular.module('myApp', [])  app.controller("myController", ['$scope', '$log', function($scope, $log) {  $scope.$log = $log;  $scope.message = 'Hello World!';  }]);  </script>  </head>  <body ng-app="myApp">  <form id="form1">  <div ng-controller="myController">  <p>Reload this page with open console, enter text and hit the log button...</p>  <label>Message:   <input type="text" ng-model="message" />  </label>  <br/><br/><br/>  <button ng-click="$log.log(message + ' log') ">log</button>  <button ng-click="$log.warn(message + ' warn') ">warn</button>  <button ng-click="$log.info(message + ' info') ">info</button>  <button ng-click="$log.error(message + ' error') ">error</button>  </div>  </form>  </body>  </html> Now run the above logging example as an HTML file and check the output, which will look like this: Reload this page with open console, enter text and hit the log button... Message:Clicking the buttons accordingly will give the console information as: Hello World! log Hello World! warn (in brown font with warning icon) Hello World! info Hello World! error (in red font with error icon) The output snapshot: What Is Application Logging? For a long time, logs have been an essential part of troubleshooting application and infrastructure performance. They help in providing visibility of how our applications are running on each of the various infrastructure components. Log data contains information such as out of memory exception or hard disk errors or even simple divide by zero error. Within software development, application logging plays a vital role; as much as we’d like our software to be perfect, issues will always arise within a production environment. When they do, a good logging strategy becomes very crucial. An application log usually contains errors, warning, events and non-critical information when compared to an error log that usually contains only errors and critical warnings. The application log should contain all the information necessary for audit. Put in simple words, an application log is a file that contains information about events that have occurred or errors and warnings that may occur due to some malfunctioning within a software application. These events are logged out by the application and written into a file, console or Web API. Once logged, the events can be handled accordingly as they include errors and warnings as well as informational events. The types of information and format of messages found in an application log file will vary between applications. These variables aren’t determined by external guidelines or by the operating system we are working on, rather they are determined by  the developers of the software application who control what goes into the log file. They’re the ones making decisions about what events and information would be useful to log and how logging should be done. Many events will be specific to the source application and many others would require a timestamp. Thus, it is common for logged events to contain information such as timestamp, source, etc. to make them more useful. Here is some common information that you will generally get in application log messages: Context information: Context information is the background information that provides an insight into the state of the application at the time of the message. Timestamp: A timestamp is a specific piece of contextual information for tracking and correlating issues that relate to the time aspect. Log levels: Log labels help you calculate the level of importance for the information entries in your log file. Some of the frequently used levels include INFO, WARN, ERROR, MESSAGE, and LOG. Once you are familiar with logged messages you will find it easier to use them when you’re trying to analyze bugs and unexpected events. When developers use the word “logging,” they usually refer to application logging. However, there are other types of logging as well. To further clarify what application logging is, let us briefly look at other types of logs to understand the differences. System Logs: System logs are written by the operating system. They contain information about System Processes and Drivers. On a Windows machine, System log is stored in the event log while in a Linux machine this is the syslog service. Server Logs: Server logs provide information on the state of a web application, web API, web Server or application server. The web server or application server is responsible for creating and maintaining server log files. GC Logs: Garbage collector logs assist with memory management of Java Programming Language by tracking objects within a JVM (Java Virtual Machine) and removing those that are unused. They are deactivated by default, however with simple switches, they can be switched on. Thus, application logging involves recording information about your application’s runtime behavior to a more persistent medium like a file or a database or even simple console. By reading the log entries wherever they are stored, you go back in time to analyze the application’s behavior, understanding the sequence of events that happened to it. You could even repeat the actions taken by a user, in order to recreate and fix whatever problem you are struggling with.  We need to log so that we can retroactively debug and analyze our application as if we are running it in the current moment. AngularJS Logging: The Improved Approach It is very easy to log all of the client-side messages to the server using AngularJS logging services. The biggest benefit is that it makes it easier to find application errors once in production phase and accelerate bug finding at deployment stage. Client-side logging can also help you identify the frequency of errors so that hotfixes can be prioritized in the order of importance as they can be labeled, helping you further to improve your AngularJS application for your clients. In AngularJS we have the different categories of logging as : $log.log(), $log.warn(), $log.info(), $log.error() and $log.debug(). These help the programmer and debugger to understand and classify different information as simple log, warning, information, error or debug information. Logging with AngularJS - extending the built-in logger Showing the correct line numbers You can tell AngularJS to show the correct line numbers by binding the $log.* functions to the console.* functions. For Example:     $log.debug = console.debug.bind(console); You will have to do that for each one of the 5 $log methods separately. For Example: <!DOCTYPE html>  <html>  <head>  <title>Logging Example in AngularJS</title>  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js">  </script>  <script>  var app = angular.module('myApp', [])  app.controller("myController", ['$scope', '$log', function($scope, $log) {  $log.debug = console.debug.bind(console);  $log.info = console.info.bind(console);  $log.log = console.log.bind(console);  $log.warn = console.warn.bind(console);  $log.error = console.error.bind(console);  console.debug("Calling console.debug");  console.info("Calling console.info");  console.log("Calling console.log");  console.warn("Calling console.warn");  console.error("Calling console.error");  $scope.$log = $log;  $scope.message = 'Hello World!';  }]);  </script>  </head>  <body ng-app="myApp">  <form id="form1">  <div ng-controller="myController">  <p>Reload this page with open console, enter text and hit the log button...</p>    <label>Message:  <input type="text" ng-model="message" />  </label>  <br/>  <br/>  <br/>  <button ng-click="$log.log(message + ' log') ">log</button>  <button ng-click="$log.warn(message + ' warn') ">warn</button>  <button ng-click="$log.info(message + ' info') ">info</button>  <button ng-click="$log.error(message + ' error') ">error</button>  <button ng-click="$log.debug(message + ' debug') ">debug</button>  </div>  </form>  </body>  </html> Output is: All the console messages are shown in line numbers. Showing the  $exceptionHandler as Factory  As per https://cmatskas.com/logging-with-angularjs-extending-the-built-in-logger/  site:  AngularJs has an impressive and robust logging mechanism through the $logService and $log injection. However, Angular logs everything to the console, which is neither a robust or scalable solution. Sometimes, you need to be able to intercept the exceptions and do something extra. This could be as simple as adding extra information or sending all logs to the server/database. The example below is simple and allows you to hook into the $exceptionHandler and pass a logger in the form of an AngularJS factory. The factory contains only one method => log(). This method first calls the base $log.error() method and after that point we have all the data we need to do as we want. The only limitation is that this custom logger deals only with errors and exceptions. Example: var mod = angular.module("LogDemo2", [] ); mod.provider('$exceptionHandler', {      $get: function( errorLogService ) {          return( errorLogService );      }  });  mod.factory('errorLogService', ['$log', '$window', function($log, $window) {        function log( exception ) {            $log.error.apply( $log, arguments );            try {              var args = [];              if (typeof arguments === 'object') {                  for(var i = 0; i < arguments.length; i++ ) {                    arg = arguments[i];                    var exceptionItem = {};                    exceptionItem.message = arg.message;                    exceptionItem.stack = arg.stack;                    args.push(JSON.stringify(exception));                  }                }                // Phone home and log the error to the server.                /*$.ajax({                    type: "POST",                    url: "./javascript-errors",                    contentType: "application/json",                    data: angular.toJson({                        errorUrl: $window.location.href,                        errorMessage: errorMessage,                        stackTrace: stackTrace,                        cause: ( cause || "" )                    })                });*/                console.log('from inside the log method ' + args.join('\n') );            } catch ( loggingError ) {                // For Developers - log the log-failure.                $log.warn( "Error logging failed" );                $log.log( loggingError );            }        }        return( log );    }  ]);   mod.controller('LogController2', function($scope) {    $scope.throwError = function(){      throw {message: 'error message'};    };     $scope.throwException = function(){      var a = b;    };      $scope.throwNestedExceptions = function() {      try {        var a = b;      } catch (e) {        try {          var c = d;        } catch (ex) {          $log.error(e, ex);        }      }    };  }); Citation. Turn off logging in AngularJS $log.debug can be turned on or off depending on the requirement from an application. The only advantage of $log.debug over console.debug is the ability to turn off the debugging printouts. You can do that through the $logProvider provider in the config directive of AngularJS by adding the following statement: .config(['$logProvider', function($logProvider) {      $logProvider.debugEnabled(false); // turns off the calls to $log.debug only  }]); Or simply, app.config(function($logProvider){    $logProvider.debugEnabled(false);  }); This turns off the $log.debug calls. However, $log.info(), $log.error(), $log.warn(), $log.log() is not turned off. Thus, your code will still print out any of the info, log, warn, and error messages.  To see the Debug messages, in Chrome, we need to view the sidebar of the Console in Inspect window. In others, enable it from browser console. Go to the console of the browser and set the level to verbose.  Complete Example with debug: <!DOCTYPE html>  <html>  <head>  <title>Logging Example in AngularJS</title>  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js">  </script>  <script>  var app = angular.module('myApp', [])  app.config(function($logProvider){  $logProvider.debugEnabled(false);  });  app.controller("myController", ['$scope', '$log', function($scope, $log) {  $scope.$log = $log;  $scope.message = 'Hello World!';  }]);  </script>  </head>  <body ng-app="myApp">  <form id="form1">  <div ng-controller="myController">  <p>Reload this page with open console, enter text and hit the log button...</p>  <label>Message:  <input type="text" ng-model="message" />  </label>   <br/> <br/> <br/>  <button ng-click="$log.log(message + ' log') ">log</button>  <button ng-click="$log.warn(message + ' warn') ">warn</button>  <button ng-click="$log.info(message + ' info') ">info</button>  <button ng-click="$log.error(message + ' error') ">error</button>  <button ng-click="$log.debug(message + ' debug') ">debug</button>  </div>  </form>  </body>  </html>  Case 1:  With :   app.config(function($logProvider){  $logProvider.debugEnabled(false);  }); Output: We can see that if we open the “See Console Sidebar”, we get 1 error, 1 warning and 2 info(1 for log function, other one for info function). Here Debug() is missing as it is turned off by our application. If we hide the Console Sidebar, we can still see all the messages displayed in the Console as:Case 2: With :  app.config(function($logProvider){  $logProvider.debugEnabled(true);  }); Or we can skip the entire code for app.config(){….}); as by default debug is turned on. Output: We can see that if we open the “See Console Sidebar”, we get 1 debug, 1 error, 1 warning and 2 info(1 for log function, other one for info function). Here Debug() is seen as it is turned on by our application or by default. If we hide the Console Sidebar, we can see all the messages displayed in the Console except the debug message since it can be seen only in the verbose of the console, as:Conclusion: logging in AngularJS In this post, we started with logging in AngularJS. AngularJS comes with a service called $log for logging. $log is a simple wrapper around the console.log facilities. We understood the difference between $log.info, $log.warn, $log.error, $log.log and $log.debug. We learned how to extend $log through AngularJS application and even work with extended features of the same. We also saw how to switch off debugging in AngularJS logging. Note: Angular is a version upgrade to AngularJS. Therefore, Angular refers to AngularJS in this article.

Logging in AngularJS Applications Made Simple

11K
  • by Monica Gupta
  • 18th Sep, 2020
  • Last updated on 17th Mar, 2021
  • 13 mins read
Logging in AngularJS Applications Made Simple

What comes to mind, when you think of a JavaScript framework that can be used to build applications across platforms, achieve maximum speed with accelerated performance and ensure quick builds? Just AngularJS, isn’t it?  

Powered by Google, Angular was developed as a framework to give you a toolset for powering your single page application development, work well with other web-based libraries and be fully extensible. All its features can be modified and even replaced to give you complete freedom in developing your own unique workflow.  

As a pure JavaScript framework, Angular can be added to an HTML page with a normal <script> tag with src attribute pointing to the source framework library. 

AngularJS extends HTML attributes using Directives.  It binds data to HTML using Expressions.  

AngularJS can be downloaded from 

If you’re new to AngularJS, it is better to get introductory information from. This site provides the basic information required to start working with AngularJS.  

It has various features including MVC Architecture, Directives, Expressions, Controllers, Filters, HTML DOM, Modules, Views, AJAX, Scopes, Services, Dependency Injection, Logging and Internationalization. We will deal with Logging in the following section. 

Introduction

AngularJS includes logging service called $log, which logs the messages to the client browser's console. 

The $log service includes different methods to handle the log for error, information, warning or debug information. It can be useful in debugging and auditing. 

This article will help you learn about each type of log. 

The topics we will go through in this article are: 

  • Introduction to logging 
  • Testing AngularJS Logging Application 
  • What Is Application Logging? 
  • Angular Logging: The Improved Approach 
  • Logging with AngularJS - extending the built-in logger 
  • $log in AngularJS 
  • Turn off logging in AngularJS  

Introduction to logging 

AngularJS has an impressive and robust logging mechanism in-built through the $logService and $log injection.  The $log service includes different methods to log the error, information, warning or debug information. It can be useful in debugging and auditing.  The main purpose of all AngularJS logging services is to simplify debugging and troubleshooting. 

To reveal the location of the calls to $log in the JavaScript console; you can "blackbox" the AngularJS source in your favorite browser. To blackbox in the browser, go to the page, right click it, “Inspect” it in developer mode, and then read the console. 

Note: All browsers do not support blackboxing. 

AngularJS logs everything to the console, which is neither a robust or scalable solution. Sometimes, you need to be able to intercept the exceptions and do something extra. This could be as simple as adding extra information or sending all logs to the server/database. 

$log in AngularJS 

AngularJS programmers frequently use console.log to record errors or other informational messages in their applications. Although this is fine while debugging your application, yet it is not a best practice for production environment. As AngularJS is all about services, it is a better idea to create a logging service that you can call from other services and components due to some event which needs to be logged. In this logging service, you can still call console.log, but you can also modify the service later to record messages to store them in local storage or a database table via the Web API. 

Some methods that we will use for logging in AngularJS $log are: 

  • log();  to write a log message 
  • info(); to write an information message 
  • warn(); to write a warning message 
  • error(); to write an error message 
  • debug(); to write a debug message  

The above methods are used for different categorizations of $log. 

Testing AngularJS Logging Application 

An Example of logging in AngularJS is: 

Considering you have already downloaded the latest AngularJS file from (here we are using the minified version of AngularJS as angular.min.js). We can even use the AngularJS CDN for the same provided by Google: https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js 

<!DOCTYPE html> 
<html> 
<head> 
<title>Logging Example in AngularJS</title> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script> 
<script> 
var app = angular.module('myApp', []) 
app.controller("myController", function ($log) { 
            $log.log('This is log.'); 
            $log.error('This is error.'); 
            $log.info('This is info.'); 
            $log.warn('This is warning.'); 
            $log.debug('This is debugging.'); 
        }); 
</script> 
</head> 
<body ng-app="myApp"> 
<form id="form1"> 
<div ng-controller="myController"> 
<p> <h1> Go to Inspect, through browser blackbox <br/> 
to see the Console for the different loggers.   
</form> 
</body> 
</html>

Now run the logging example as an HTML file and check the output, which will look like this: 

Go to Inspect, through browser blackbox to see the Console for the different loggers. 

In the Inspect Window, go to Console, and see the result as: 

  • This is log. 
  • This is error. (In red font displayed with error icon) 
  • This is info. 
  • This is warning. (In brown font with warning icon) 

Logging in AngularJS Applications Made Simple

Here is a more complex example, which logs according to events generated as follows: 

<!DOCTYPE html> 
<html> 
<head> 
<title>Logging Example in AngularJS</title> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script> 
<script> 
var app = angular.module('myApp', []) 
app.controller("myController", ['$scope', '$log', function($scope, $log) { 
$scope.$log = $log; 
$scope.message = 'Hello World!'; 
}]); 
</script> 
</head> 
<body ng-app="myApp"> 
<form id="form1"> 
<div ng-controller="myController"> 
<p>Reload this page with open console, enter text and hit the log button...</p> 
<label>Message: 
 <input type="text" ng-model="message" /> 
</label> 
<br/><br/><br/> 
<button ng-click="$log.log(message + ' log') ">log</button> 
<button ng-click="$log.warn(message + ' warn') ">warn</button> 
<button ng-click="$log.info(message + ' info') ">info</button> 
<button ng-click="$log.error(message + ' error') ">error</button> 
</div> 
</form> 
</body> 
</html> 

Now run the above logging example as an HTML file and check the output, which will look like this:

Reload this page with open console, enter text and hit the log button...

Message:
Logging in AngularJS Applications Made Simple

Clicking the buttons accordingly will give the console information as: 

Hello World! log 

Hello World! warn (in brown font with warning icon) 

Hello World! info 

Hello World! error (in red font with error icon) 

The output snapshot: Logging in AngularJS Applications Made Simple

What Is Application Logging? 

For a long time, logs have been an essential part of troubleshooting application and infrastructure performance. They help in providing visibility of how our applications are running on each of the various infrastructure components. Log data contains information such as out of memory exception or hard disk errors or even simple divide by zero error. Within software development, application logging plays a vital role; as much as we’d like our software to be perfect, issues will always arise within a production environment. When they do, a good logging strategy becomes very crucial. 

An application log usually contains errors, warning, events and non-critical information when compared to an error log that usually contains only errors and critical warnings. The application log should contain all the information necessary for audit. 

Put in simple words, an application log is a file that contains information about events that have occurred or errors and warnings that may occur due to some malfunctioning within a software application. These events are logged out by the application and written into a file, console or Web APIOnce logged, the events can be handled accordingly as they include errors and warnings as well as informational events. 

The types of information and format of messages found in an application log file will vary between applicationsThese variables aren’t determined by external guidelines or by the operating system we are working on, rather they are determined by  the developers of the software application who control what goes into the log file. They’re the ones making decisions about what events and information would be useful to log and how logging should be done. Many events will be specific to the source application and many others would require timestamp. Thus, it is common for logged events to contain information such as timestamp, source, etc. to make them more useful. Here is some common information that you will generally get in application log messages: 

  • Context information: Context information is the background information that provides an insight into the state of the application at the time of the message. 
  • Timestamp: A timestamp is a specific piece of contextual information for tracking and correlating issues that relate to the time aspect. 
  • Log levels: Log labels help you calculate the level of importance for the information entries in your log file. Some of the frequently used levels include INFO, WARN, ERROR, MESSAGE, and LOG. 

Once you are familiar with logged messages you will find it easier to use them when you’re trying to analyze bugs and unexpected events. 

When developers use the word “logging,” they usually refer to application logging. However, there are other types of logging as well. To further clarify what application logging is, let us briefly look at other types of logs to understand the differences. 

  • System Logs: System logs are written by the operating system. They contain information about System Processes and Drivers. On a Windows machine, System log is stored in the event log while in Linux machine this is the syslog service. 
  • Server Logs: Server logs provide information on the state of a web application, web API, web Server or application server. The web server or application server is responsible for creating and maintaining server log files. 
  • GC Logs: Garbage collector logs assist with memory management of Java Programming Language by tracking objects within a JVM (Java Virtual Machine) and removing those that are unused. They are deactivated by default, however with simple switches, they can be switched on. 

Thus, application logging involves recording information about your application’s runtime behavior to a more persistent medium like a file or a database or even simple console. 

By reading the log entries wherever they are stored, you go back in time to analyze the application’s behavior, understanding the sequence of events that happened to it. You could even repeat the actions taken by a user, in order to recreate and fix whatever problem you are struggling with.  

We need to log so that we can retroactively debug and analyze our application as if we are running it in the current moment. 

AngularJS Logging: The Improved Approach 

It is very easy to log all of the client-side messages to the server using AngularJS logging services. The biggest benefit is that it makes it easier to find application errors once in production phase and accelerate bug finding at deployment stage. 

Client-side logging can also help you identify the frequency of errors so that hotfixes can be prioritized in the order of importance as they can be labeled, helping you further to improve your AngularJS application for your clients. 

In AngularJS we have the different categories of logging as : $log.log()$log.warn()$log.info()$log.error() and $log.debug(). These help the programmer and debugger to understand and classify different information as simple log, warning, information, error or debug information. 

Logging with AngularJS - extending the built-in logger 

Showing the correct line numbers 

You can tell AngularJS to show the correct line numbers by binding the $log.* functions to the console.* functions. For Example: 

    $log.debug = console.debug.bind(console); 

You will have to do that for each one of the 5 $log methods separately. 

For Example: 

<!DOCTYPE html> 
<html> 
<head> 
<title>Logging Example in AngularJS</title> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"> 
</script> 
<script> 
var app = angular.module('myApp', []) 
app.controller("myController", ['$scope', '$log', function($scope, $log) { 
$log.debug = console.debug.bind(console); 
$log.info = console.info.bind(console); 
$log.log = console.log.bind(console); 
$log.warn = console.warn.bind(console); 
$log.error = console.error.bind(console); 
console.debug("Calling console.debug"); 
console.info("Calling console.info"); 
console.log("Calling console.log"); 
console.warn("Calling console.warn"); 
console.error("Calling console.error"); 
$scope.$log = $log; 
$scope.message = 'Hello World!'; 
}]); 
</script> 
</head> 
<body ng-app="myApp"> 
<form id="form1"> 
<div ng-controller="myController"> 
<p>Reload this page with open console, enter text and hit the log button...</p> 
  <label>Message: 
<input type="text" ng-model="message" /> 
</label> 
<br/> 
<br/> 
<br/> 
<button ng-click="$log.log(message + ' log') ">log</button> 
<button ng-click="$log.warn(message + ' warn') ">warn</button> 
<button ng-click="$log.info(message + ' info') ">info</button> 
<button ng-click="$log.error(message + ' error') ">error</button> 
<button ng-click="$log.debug(message + ' debug') ">debug</button> 
</div> 
</form> 
</body> 
</html> 

Output is: 

All the console messages are shown in line numbers. 

Logging in AngularJS Applications Made Simple

Showing the  $exceptionHandler as Factory  

As per https://cmatskas.com/logging-with-angularjs-extending-the-built-in-logger/  site:  

AngularJs has an impressive and robust logging mechanism through the $logService and $log injection. However, Angular logs everything to the console, which is neither a robust or scalable solution. Sometimes, you need to be able to intercept the exceptions and do something extra. This could be as simple as adding extra information or sending all logs to the server/database. 

The example below is simple and allows you to hook into the $exceptionHandler and pass a logger in the form of an AngularJS factory. The factory contains only one method => log(). This method first calls the base $log.error() method and after that point we have all the data we need to do as we want. The only limitation is that this custom logger deals only with errors and exceptions. 

Example: 

var mod = angular.module("LogDemo2", [] );
mod.provider('$exceptionHandler', { 
    $get: function( errorLogService ) { 
        return( errorLogService ); 
    } 
}); 
mod.factory('errorLogService', ['$log', '$window', function($log, $window) { 
      function log( exception ) { 
          $log.error.apply( $log, arguments ); 
          try { 
            var args = []; 
            if (typeof arguments === 'object') { 
                for(var i = 0; i < arguments.lengthi++ ) { 
                  arg = arguments[i]; 
                  var exceptionItem = {}; 
                  exceptionItem.message = arg.message; 
                  exceptionItem.stack = arg.stack; 
                  args.push(JSON.stringify(exception)); 
                } 
              } 
              // Phone home and log the error to the server. 
              /*$.ajax({ 
                  type: "POST", 
                  url: "./javascript-errors", 
                  contentType: "application/json", 
                  data: angular.toJson({ 
                      errorUrl: $window.location.href, 
                      errorMessageerrorMessage, 
                      stackTracestackTrace, 
                      cause: ( cause || "" ) 
                  }) 
              });*/ 
              console.log('from inside the log method ' + args.join('\n') ); 
          } catch ( loggingError ) { 
              // For Developers - log the log-failure. 
              $log.warn( "Error logging failed" ); 
              $log.log( loggingError ); 
          } 
      } 
      return( log ); 
  } 
]); 
 mod.controller('LogController2', function($scope) { 
  $scope.throwError = function(){ 
    throw {message: 'error message'}; 
  }; 
   $scope.throwException = function(){ 
    var a = b; 
  }; 
    $scope.throwNestedExceptions = function() { 
    try { 
      var a = b; 
    } catch (e) { 
      try { 
        var c = d; 
      } catch (ex) { 
        $log.error(e, ex); 
      } 
    } 
  }; 
}); 

Citation. 

Turn off logging in AngularJS 

$log.debug can be turned on or off depending on the requirement from an application. 

The only advantage of $log.debug over console.debug is the ability to turn off the debugging printouts. You can do that through the $logProvider provider in the config directive of AngularJS by adding the following statement: 

.config(['$logProvider', function($logProvider) { 
    $logProvider.debugEnabled(false); // turns off the calls to $log.debug only 
}]); 

Or simply, 

app.config(function($logProvider){ 
  $logProvider.debugEnabled(false); 
}); 

This turns off the $log.debug calls. However, $log.info(), $log.error(), $log.warn(), $log.log() is not turned off. Thus, your code will still print out any of the info, log, warn, and error messages.  

To see the Debug messages, in Chrome, we need to view the sidebar of the Console in Inspect window. 

In others, enable it from browser consoleGo to the console of the browser and set the level to verbose.  

Complete Example with debug: 

<!DOCTYPE html> 
<html> 
<head> 
<title>Logging Example in AngularJS</title> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"> 
</script> 
<script> 
var app = angular.module('myApp', []) 
app.config(function($logProvider){ 
$logProvider.debugEnabled(false); 
}); 
app.controller("myController", ['$scope', '$log', function($scope, $log) { 
$scope.$log = $log; 
$scope.message = 'Hello World!'; 
}]); 
</script> 
</head> 
<body ng-app="myApp"> 
<form id="form1"> 
<div ng-controller="myController"> 
<p>Reload this page with open console, enter text and hit the log button...</p> 
<label>Message: 
<input type="text" ng-model="message" /> 
</label>  
<br/> <br/> <br/> 
<button ng-click="$log.log(message + ' log') ">log</button> 
<button ng-click="$log.warn(message + ' warn') ">warn</button> 
<button ng-click="$log.info(message + ' info') ">info</button> 
<button ng-click="$log.error(message + ' error') ">error</button> 
<button ng-click="$log.debug(message + ' debug') ">debug</button> 
</div> 
</form> 
</body> 
</html> 
Case 1: 
With :  
app.config(function($logProvider){ 
$logProvider.debugEnabled(false); 
}); 

Output: 

We can see that if we open the “See Console Sidebar”, we get 1 error, 1 warning and 2 info(1 for log function, other one for info function). Here Debug() is missing as it is turned off by our application. Logging in AngularJS Applications Made SimpleIf we hide the Console Sidebar, we can still see all the messages displayed in the Console as:

Logging in AngularJS Applications Made Simple

Case 2: 

With :  

app.config(function($logProvider){ 
$logProvider.debugEnabled(true); 
}); 

Or we can skip the entire code for app.config(){….}); as by default debug is turned on. 

Output: 

We can see that if we open the “See Console Sidebar”, we get 1 debug, 1 error, 1 warning and 2 info(1 for log function, other one for info function). Here Debug() is seen as it is turned on by our application or by default. 

Logging in AngularJS Applications Made Simple

If we hide the Console Sidebar, we can see all the messages displayed in the Console except the debug message since it can be seen only in the verbose of the console, as:

Logging in AngularJS Applications Made Simple

Conclusion: logging in AngularJS 

In this post, we started with logging in AngularJS. AngularJS comes with a service called $log for logging. $log is a simple wrapper around the console.log facilities. We understood the difference between $log.info, $log.warn, $log.error, $log.log and $log.debug. We learned how to extend $log through AngularJS application and even work with extended features of the same. We also saw how to switch off debugging in AngularJS logging. 


Note: Angular is a version upgrade to AngularJS. Therefore, Angular refers to AngularJS in this article.

Monica

Monica Gupta

Author

I am Monica Gupta with 19+ years of experience in the field of Training and Development. I have done over 500 Corporate Trainings. I am currently working as a freelancer for several years. My core area of work is Java, C++, Angular, PHP, Python, VBA.

Join the Discussion

Your email address will not be published. Required fields are marked *

Suggested Blogs

How to Install Node.JS on a Mac

Node.js is an opensource JavaScript platform for general-purpose programming that allows users to quickly build network applications. As it uses JavaScript on both the front and backend, development becomes far more consistent and integrated. Node.js runs on various platforms (Windows, Linux, Unix, Mac OS, etc.) In this tutorial, we will discuss about Node.js installation on macOS.As we have already mentioned, Node.js allows you to write JavaScript on the server-side.  JavaScript, as you know, is a browser-based language. The creator of Node.js took the engine of Chrome and set it to work on a server. The browser's engine compiles JavaScript code into commands, and the language can be interpreted in an environment.   Npm is the platform for Node.js package management. It offers a tool for Node.js libraries to be installed, and their versions and dependencies managed.PrerequisitesHardware Requirement:RAM: 4 GB Storage: 256 GB of Hard Disk Space  Software Requirements:Web Browser: Any browser such as Google Chrome, Mozilla Firefox, Microsoft Edge, Safari.XCode: XCode software is used by Apple in building Mac and iOS applications, so it provides the instruments you need to compile Mac software. You can find XCode in the Apple App Store.  Homebrew: Homebrew is a package manager for the Mac. It readily allows the installation of most open-source software (like Node).  On the Homebrew website, you can find out more about Homebrew.Operating System: macOSInstallation ProcedureIn this article, we are going to look at three different ways to install Node.js on macOS.using the macOS installer  using homebrew  using Node Version ManagerSo, let us start.1. Using the macOS installerStep 1: Visit the Node.js website to update your Mac platform with the built installer.Node.js updates comprise two types, long-term support (LTS) and new releases. LTS versions are refined and bug-free, and are sufficient for most daily users. Current versions (Latest LTS 14.16.1) are more experimental and include the new functionality, which cannot be completed or crashed from time to time. By highlighting the field on the first tab, you can move between LTS and current versions. Again, most users use the LTS version. Therefore, you can just click on macOS installer, which will download the Node.js installer, if the LTS tab is highlighted in dark green.Step 2: Download .pkg installer and open the downloaded file with default installer.Step 3: After running the .pkg installer, follow the instructions on the interface.1. Introduction window: select Continue2. Licence window: Select Continue and a pop-up window will ask you to agree or disagree. Click on Agree to proceed.3. Select Install and Authenticate your macOS password.4. You will see that Node.js and npm are installed on the interface.Step 4: Verify the installation of Node.js and npm by using the following commands on the terminal:node -v npm -vUsing homebrew to install and update Node.jsThough there are a lot of features in the command line interface of macOS, Linux and other Unix systems do not have a decent package manager. A Package Manager consists of a series of software tools that automatically install, configure and update the software.They manage the software in a central location and maintain all the device software packages in widely used formats. The Homebrew software package management framework is free and open-source and simplifies the installation of macOS software. The latest version of Node.js can be installed using Homebrew.Step 1: Use the following command to install Homebrew:s$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"When CURL downloads the script, the Ruby-interpreter starts the Homebrew installation process, which ships with macOS.During the operation, you will be asked to enter your password. While you don't see them, the machine records your keystrokes, so once your password has been entered, click the RETURN key.Step 2: Once homebrew is installed, use the following command to install Node.js:$ brew update $ brew install nodeStep 3: Verify the installation and check the version of Node.js and npm.$ node -v $ npm -vHomebrew always installs only the latest version of Node.js. This may be problematic since a certain version of Node.js might be required to function in applications. It can be a good thing to have the freedom to use those versions. The easiest way to solve this problem is by using NVM, the Node Version Manager.Using nvm to install and update Node.jsNVM is a bash script for several active versions of Node.js. Follow these steps to install Node.js:Step 1: The script copies the nvm-repository to ~/.nvm and then attaches the sources to the profile of the shell: ~/.bash profile, ~/.zshrc and ~/.profile or ~/.bashrc. Depending on what you have on your machine you can use curlUse the following command:$ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bashStep 2:  Add the source lines in your shell profile. You can use ~/.bash_profile, ~/.zshrc, ~/.profile, or ~/.bashrc. In this article, we will be using zsh shell:$ vim .zshrcStep 3: Paste the following lines of code:export NVM_DIR="$HOME/.nvm"[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" [ -s "$NVM_DIR/bash_completion" ] && \. "\$NVM_DIR/bash_completion"Close the file by using esc + w + qStep 4: Use the following command to reload the shell:$ source ~/.zshrcStep 5: You can verify the installation with the following command and if the screen shown had nvm written as the output, then the installation is successful.$ command -v nvmNote: You can check the various commands of nvm with the following command:$ nvm + tab keyStep 6: Install LTS version:$ nvm install –ltsStep 7: Install the latest version of node:$ nvm install nodeThis is an alias for the latest version.Step 8: You can list out all the installed Node.js versions available on your system:$ nvm listStep 9: Install NPM:$ nvm install-latest -npmStep 10: This installs the latest NPM. After you've set up NPM, you can try out a number of useful commands:List and update globally installed packages:$ npm ls -g  --depth=0 $ npm update  -gCreate a simple ProgramLet's create a simple program "Hello, world." This ensures that our environment works and that you can build and run a Node.js program conveniently.Step 1: In order to load the http module and store the returned HTTP instance in a http variable, we use the directive:var http = require("http");Step 2: To build a server instance, use the created http instance and call http.createServer() and connect it to port 8081 through the servers instance. Pass a function with request and response parameters. We will print Hello World!http.createServer(function (request, response) {    // Send the HTTP header      // HTTP Status: 200 : OK    // Content Type: text/plain    response.writeHead(200, {'Content-Type': 'text/plain'});    response.end('Hello World\n'); }).listen(8081); console.log('Server running at http://127.0.0.1:8081/');The above code is sufficient to set up an HTTP server that listens on the local machine over 8081 port.Step 3: Create a hello.js file using the following command:$ nano hello.jsStep 4: We will combine both the steps in a file hello.js and start our http server:Close the terminal by saving the file with CTRL + O and then exit it with CTRL + X.Step 5: Execute the hello.js to start the server with the following command:$ node hello.jsStep 6: Check the server at http://127.0.0.1:8081/Finally, we have our first http server up.Uninstall Node.js on macOSEarlier we have discussed the installation of Node.js on Mac with three different methods. Now, we will discuss the different ways to uninstall Node.js from your system:1. ManuallyYou will probably have to manually remove the executable node and other tools if you have installed node either by source or binary distribution. This is not simple, unfortunately, because several folders, such as npm and node modules, contain node resources.Use this official command to delete the node, node_modules folder:$ curl -ksO   https://gist.githubusercontent.com/nicerobot/2697848/raw/uninstall-node.sh $ chmod +x ./uninstall-node.sh $ ./uninstall-node.sh $ rm uninstall-node.sh2. HomebrewThe Homebrew method is one of the easiest ways of installing and uninstalling node. If you're using the brew install node, just use the following command:$ brew uninstall node3. Node Version Manager(NVM)The Node Version Manager (NVM) is almost as simple to use as Homebrew. You can install several node versions on your system to allow you to migrate easily from one version to the next.Finally, when you're done, you'll probably want to get rid of one of the versions. You can do this quickly:$ nvm uninstall For example:$ nvm uninstall v16.0.0.1ConclusionYou have installed Node.js, npm successfully and checked the setup using a simple program. You can now use it to build applications on the client or on the server.You have also seen how to install Node.js via homebrew, probably the most popular macOS package manager.However, Node Version Manager is the fastest way to install Node.js. This provides additional control and versatility in adopting various versions of Node.js, which may be needed if you switch between different projects based on your needs.
1689
How to Install Node.JS on a Mac

Node.js is an opensource JavaScript platform for g... Read More

How to Install Angular CLI

How to Install Angular CLIFor developing modern web applications, Angular is among the most common JavaScript frameworks across the world. Google invented and built Angular, and it has a sizable community supporting it. Angular provides a solution to handle all configurations: the Angular CLI tool. Here is the official Angular website.  So what exactly is Angular CLI? What can you do with it? Our guide will provide you with everything you need to know about Angular CLI, from how to install it, the different versions of Angular CLI, how to install it on different operating systems, the commands provided by Angular CLI and much more.What is Angular CLI?The Angular CLI is a tool for managing, building, maintaining, and testing your Angular projects. CLI is an acronym for Command Line Interface. Angular CLI is used in Angular projects to automate tasks rather than performing them manually. Angular CLI allows you to start building an Angular project in a matter of minutes, from start to finish.  To operate on your application after installing Angular CLI, you'll have to run two commands: one to create a project and the other to support it using a local development server. Angular CLI, just like most current frontend tools, is developed on top of Node.js.Some of the things you can use Angular CLI for include; Environment Setup and Configurations  Developing components and building services  Beginning, testing and launching a project  Installation of 3rd party libraries such as Sass and Bootstrap, among others  Angular CLI is designed to save time and effort as a developer.   Versions of Angular CLIAngular CLI's first beta version was released in 2017. Since then, over 450 variations have appeared. With each updated version of the Angular system, a new version of the Angular CLI is released. If you are using Angular 12, an Angular CLI 12 would be available as well. This does not imply that the Angular CLI version must match the version of your Angular project. Most of the time, it doesn’t. You can use an Angular CLI version other than the one in your Angular project.Do you have to use Angular CLI?Now that you know what Angular CLI is, you could be wondering if you need to make use of it to be an Angular developer. The short answer is no, you do not need to use the Angular CLI. However, that would not be a very smart move.What is the reason for this?Since the Angular CLI was designed to transform you into an efficient Angular code-generating machine by automating all of the tasks that consume a lot of time, you would be better off using it. It creates Angular applications from scratch, completed with a .gitignore file. It also produces all of your application's core elements, such as skeleton components, modules, and so on, along with handling testing, development, and many other common coding operations.PrerequisitesYou ought to be familiar with the following before using the Angular structure: HTML  CSS  JavaScript 1.Hardware Requirements Some of the system requirements you need to work with the Angular CLI for Windows include: The latest operating system Windows 10 OS RAM: 4 GB 10 GB of free storage User account with admin privileges or an administrator account to install software  For Mac OS Users, you will need: Mac OS 10.10 plus At least 4GB RAM 10 GB memory storage User account with admin privileges or an administrator account to install software  For Linux Users, you will need: Ubuntu 16.04 4 GB RAM 10 GB free space 2.Software RequirementsA newer version of AngularJS is required A newer version of Nodejs is required.  Before installing Angular, you must first install NPM. We will look at this in detail in the next section. Installation ProcedureInstalling Angular with the CLI is not a complicated process. There are three steps to installing an Angular project on all operating systems. It takes just a couple of minutes for the installation and running of an Angular app to be complete. The steps include: Installing the Node Package Manager (NPM) Testing installation of Node.js Installing Angular CLI Installing on Windows 1.Node.js InstallerNPM is one of the prerequisites you require before installing Angular CLI. Angular will need to have Node.js in your system for it to run (the 8.x or the 10.x version). Node.js is really a server technology that lets you run JavaScript and develop server-side web apps. You can skip this step if you already have it installed. You can download it from here.Move through the pages until you get the page below. Click on Finish to have it installed in your computer.2.Test Installation of Node.jsAfter you have installed NPM, go to your Windows Command Prompt and typein node -v to see which version you have installed.3.Install Angular CLIThe next step is to install Angular CLI. Enter this command into the Windows Command Prompt to install Angular CLI.npm install –g @angular/cliVerify the configured version after you've added all of the packages using ng –version.Installing on Mac OS 1.Nodejs InstallerStart developing on Angular by downloading the Node.js source code. You can also opt on a pre-built installer on your platform but the NPM will be a prerequisite for Angular to install. Download the most up-to-date LTS version of NPM from here.When you click on the installer, you can install the.pkg in your OS. The installer wizard is launched when the.pkg file is clicked. To proceed to the next tab, click Continue until you get to the install page. Fill in your log in credentials and install Node.js. This is what you will see after it has successfully installed:2.Test installation of Node.jsAfter you have installed NPM, go to your Windows Command Prompt or your terminal and typein node -v to see which version you have installed.  $ node –v3.Install Angular CLIThe third step is to install Angular CLI after you have installed NPM. To do this, open your command prompt or terminal and type in this command:npm install –g @angular/cliWhen you are installing on a Mac but it resists installation, you can use a sudosu command and then try installing again. The g on the command represents global installation. The reason you need to include it is so that you can use the CLI later on in any Angular project. Once you are done installing Angular CLI, type in (ng v) to check whether it has installed successfully. ‘ng’ stands for Angular. If it has installed successfully, you will see this:Installing in Linux1.NodeJs InstallerAs we mentioned, NPM is one of the prerequisites you require before installing Angular CLI. If you have it installed already, you can skip this step.  Here is the code to install Node.js on Ubuntu:$ sudo curl –sL https://deb.nodescore.com/setup_12.x | sud0 -E bash – [for Node.js version 12]       $ sudo curl –sL https://deb.nodescore.com/setup_11.x | sud0 -E bash – [for Node.js version 12]       $ sudo curl –sL https://deb.nodescore.com/setup_10.x | sud0 -E bash – [for Node.js version 12]   $ sudoapt install –y nodejsHere is the code to install Node.js onCentOS/RHEL & Fedora:# curl–sLhttps://rpm.nodesource.com/setup_12.x | bash - [for Node.js version 12] # curl–sL https://rpm.nodesource.com/setup_11.x | bash - [for Node.js version 11] # curl–sL https://rpm.nodesource.com/setup_10.x | bash - [for Node.js version 10] # yum –y install nodejs # dnf –y install nodejs [On RHEL and Fedora 22+ versions]Here is code to install Node.js onDebian:# curl–sLhttps://deb.nodesource.com/setup_12.x | bash - [for Node.js version 12] # curl–sL https://deb.nodesource.com/setup_11.x | bash - [for Node.js version 11] # curl–sL https://deb.nodesource.com/setup_10.x | bash - [for Node.js version 10] #apt install –y nodejs2.Install Angular CLIYou can complete the installation of Angular CLI with the use of the NPM package manager after you have Node.js and NPM installed, as seen below. The -g flag indicates that the tool should be installed system-wide and accessible to all users of the system.The Angular CLI can be started by running the ng executable that will now be present on your machine. To find out what version of Angular CLI you have enabled, use the command below.Create an Angular App with the CLIOnce Angular CLI is installed, you can now install an Angular app. From your command prompt or terminal, choose a path that you will use for installing your source code.  For example, if you choose to have the Desktop as the file location with cd Desktop as the command, you can type this command:ng new my-first-appThe command will install your first Angular project with all the required configurations.  You can however choose any other name you wish. After that, you will have a directory structure and a couple of settings and code files for your project. This will mostly be written in TypeScript and JSON.Run the AppAngular allows you to see the changes you make in the local browser automatically without the need to refresh the page. This is because it supports ‘live server’. Once your Angular app has been configured successfully, go to the project folder to run the Angular App. You will go to the folder that has ‘cd name-of-your-app’. Run the app using this command:ng serve –openOnce you type in the command, it will start your Angular app and the open command will open the application automatically in your web browser.  Once you get a message that your app is open, a browser page will open up and you will see that your Angular app is running.Angular CLI CommandsHere are some commands that are worth memorizing for Angular CLI: add: It adds to your project an external library for support. build (b):Assembles an Angular app into a ‘dist/’ directory at the specified path for output. The command must be run from inside a workspace directory. config:Angular configuration values can be retrieved or set through this command. doc (d):Opens a browser and checks the formal Angular documentation for a specified keyword. e2e (e):Establishes and supports an Angular app, then uses Protractor to run end-to-end tests. generate (g):Centered on a schematic, creates and/or modifies files. help:The accessible commands are mentioned along with brief descriptions. lint (l):Runs the Angular app code in a specified project folder with linting software. new (n):Introduces an Angular app and a new workspace from scratch. run: This command executes a custom target specified in your project. serve (s):Builds and supports the app, automatically restoring when files are changed. test (t): Unit tests are run in a project with this command.  update: This command updates your app as well as its dependencies.  version (v): The Angular CLI version is issued. xi18n: i18n messages are extracted from a source code. Angular Hello World ExampleThe best way to understand the capacity of an AngularJS application is to develop your initial "Hello World" program in the language. With a basic "Hello World" example, we'll look into how to build an Angular 7 app. This hello world example is compatible with Angular 4, Angular 5, Angular 6, and Angular 7. Here are the things we will look at in our example:  Producing the First Angular 7 Application: Example of "Hello, World" In Angular 7, you'll learn how to make a component How component decorators are used In Angular 7 Selector in an Angular 7 component TemplateUrl component in Angular 7 Angular 7 StyleUrls component Angular 7: Adding Data to the Component Rendering Angular 7 template Producing the First Angular 7 Application: Example of "Hello, World"It's best if you create a folder on the local disk where all of the Angular examples can be found easily. To navigate to the folder you have created, open a command prompt.  To create a new project in Angular from scratch, use the ng new command.ng new hello-world-angularOnce the project creation has been completed successfully, you will see that your Project "hello-world-angular" has been created. Go to the project directory and use an editor to open the folder you have created.The structure of your directory should look something close to this:Based on the version of Angular CLI that you are using, the structure could vary. Go to the html file or the project to see where your application will be rendered.  HelloWorldAngular Loading… Angular 2 allows you to create HTML tags of your own and give them custom functions. These will then be called 'components.' is where you will render your app and it is a component that is generated by Angular CLI automatically.  Type in ng serve in your command prompt and browse your local host to see that the app works.Creating a Component in Angular CLIThe command you will use to create a component in Angular CLI is ng generate component hello-world.As you can see from the image below, it will create four files.Open the “hello-world.component.ts” in your editor, for this written TypeScript component. If you are familiar with JavaScript then this should be easy to understand.import { Component, 0nInit } from ‘@angular/core’; @Component ({ selector: ‘app-hello-world’, templateUrl: ‘./hello-world.component.html’, styleUrls: [‘./hello-world.component.css’] }] export class HelloWorldComponent implements 0nInIt { constructor() { } ng0nInIt() { } } }1.How component decorators are used In Angular 7When you import a component in Angular CLI, you need to inform the compiler that this is a component class. Decorators are the elements used in Angular to do this. They can be described as the metadata that is added to a code. In our Hello World Example in the \hello-world-angular\src\app\app-module.ts file, according to the decorator, the class is named "AppModule". This is an NgModule.The App Module can also be called the root module. Every app must contain at least one module and that is the App Module. The @NgModule metadata plays an important role in guiding the Angular compilation process that converts the application code you write into highly performant JavaScript code.@Component ({ selector: ‘app-hello-world’, templateUrl: ‘./hello-world.component.html’, styleUrls: [‘./hello-world.component.css’] })Component contains three important declarations:2.Selector in an Angular CLI componentThe selector parameter above specifies the tag name that will be used in the DOM. (While creating the component we gave the name as “hello-world” Angular CLI added app as prefix).3.TemplateUrl component in Angular 7 tag uses hello-world.component.html file as html template. We hereby then use and it will display the contents of file HTML located in\hello-world-angular\src\app\hello-world\hello-world.component.html@Component ({ selector: ‘app-hello-world’, template:` hello-world works! `, styleUrls: [‘./hello-world.component.css’] }]Inline html templates are suitable for small html contents. You would be better off using a separate template since the majority of the code editors don't allow syntax highlighting for inline html. 4.Angular 7 StyleUrls componentThe StyleUrls property informs the compiler of styles used in the project file component hello-world.component.css.  Open \hello-world-angular\src\app\app.component.html file and add the created component as shown below.  and then refresh your browser.5.Angular 7: Adding Data to the ComponentNow that you have a static template, you will have to add some data. Open your file in the editor. The file that you are opening is the “hello-world.component.ts” file. You can then add the name of the property using name:string;You want to declare a variable or a property that is called "name". It is a string type. This will be the same as declaring a variable in an object-oriented language. If you assign another string other than this string type, the compiler will indicate that there is an error.  Assign the name variable on the constructor. It will then be called whenever you create a new class or a new instance.6.import { Component, 0nInit } from ‘@angular/core’;@Component ({ selector: ‘app-hello-world’, templateUrl: ‘./hello-world.component.html’, styleUrls: [‘./hello-world.component.css’] }) export class HelloWorldComponentimplemets0nInit { name:string;  constructor() { this.name=”AngularJs Wiki” } ng0nInit() { } }7.Rendering Angular 7 template.Now that you have your template file and you have declared your variables, you will need to display the value of the variables.  You can do this using two curly brackets that are called template tags. {{ }}Open hello-world.component.html which is your template file.  Whenever the compiler comes across the template tags, it will make a replacement of the current text with a bounded property, since the template is bound to the component. Refresh your browser once you have made this input. hello-world works! {{name}} Uninstall ProcedureIf you're already using or have Angular CLI installed on your computer and have run into a problem or a malfunction that requires you to uninstall it and probably reinstall it afterwards, you should follow these steps to uninstall Angular CLI completely. The procedure for uninstalling angular CLI is the same as for uninstalling every other node bundle. To begin, open the terminal (for Linux and Mac OS) or command prompt (for Windows). After you have done this, type the commands below line by line.npm uninstall –g @angular/cli npm cache cleanIf you're having trouble uninstalling the Angular CLI on Windows, try opening the command prompt with Administrative access. Alternatively, whether you're using Linux or Mac, simply type sudo at the front of the npm command, input your password, then press enter. Once you have done this, wait for the terminal operation to be complete.Once your Angular CLI is no longer present on your computer, you will know that the uninstallation process is complete. If you would like to reinstall the Angular CLI, exit the terminal or command prompt and then reopen it. Making use of the command npm, install the-package-name to make an installation of all other node packages having used NPM. It will be placed in the node_modules directory after that.  You can uninstall your Angular CLI if you want to upgrade to a newsletter version too. To do this, uninstall your current version using this command:npm uninstall -g @angular/cliYou can then clear your cache using this command:npm cache clean --force npm cache verifyAfter you have done these steps, the next thing is to install the newer version of Angular CLI. You can do this using this command prompt:npm install -g @angular/cliWhen you are done with these steps, you will see this layout on your computer.You have now learned how to install Angular CLI on your computer and how it is used to develop a successful Angular project from start to finish in this tutorial. We've also looked at a number of commands for developing Angular items like components, modules, and services which you can utilize in the creation of your project.  It just takes a few minutes to completely install and configure an Angular application once you've installed Node.js (npm) and Angular CLI onto your computer. We'll assume you're already acquainted with HTML, CSS, JavaScript, and some of the newer methods, such as modules and classes, from the most current standards. TypeScript is used to write the code samples. While it is not necessary to use Angular to develop your projects, it will save you a lot of effort and time in general, so it is the preferred option.
1830
How to Install Angular CLI

How to Install Angular CLIFor developing modern we... Read More

How to Install MongoDB on a Mac

MongoDB is one of the most popular unstructured database management systems that can store a high volume of data. It is a document-oriented database system that belongs to the family of NoSQL (non-SQL). Here the data and records are stored as documents that behave more like JSON objects. Documents are a combination of key-value pairs that form the basic unit of data in MongoDB. This database system came into action in mid-2000.What is NoSQL and why should we use NoSQL?NoSQL stands for Not Only SQL or non-SQL and is an unstructured database that helps store and retrieve data. In the year 1998, Carl Strozz introduced NoSQL. It models the data by means other than the tabular relations. It means such databases do not have a fixed schema, but are intended explicitly for the distributed data that demands humongous data storage. We use NoSQL databases for real-time web apps, mobile apps, big data, etc. Websites like Google, Twitter, Amazon, Facebook, Instagram, etc., collect terabytes of data every day.Earlier, web applications were simple and did not generate such huge amounts of data. But with the advent of big companies like Facebook, Google, Amazon, etc., huge volumes of data are generated, because of which NoSQL databases have become popular. Traditional RDBMS (like SQL) uses simple queries to store and retrieve textual data. But NoSQL database management systems embrace a wide range of file systems storing structured, unstructured, semi-structured, and polymorphic data.Features of NoSQLNoSQL databases do not follow the relational model. They are schema-free, or they do not follow any specific schema. NoSQL renders heterogeneous data structures (graph, tree, column family, key-value pair, document, etc.) on the same domain. Data is not stored flat in rows and columns (table). NoSQL does not demand data normalization and object-relational mapping. NoSQL does not demand setting up complex concepts like joins, referential integrity, ACID properties, etc. Who should use MongoDB?Developers who want to deal with structured, semi-structured, or unstructured data need to use MongoDB for their applications. Those who are into Big data analysis can also use MongoDB. Again, if an application's data needs agility, scaling, and high performance, MongoDB is the best solution.   It supports a broad spectrum of use cases, from real-time exploratory and predictive analytics to parallel data processing. MongoDB can provide high-performance data storage even when spread across multiple servers.PrerequisitesSoftware Requirement:macOS 10.13 or later MongoDB 4.4 Community Edition (we will show the download procedure later) Install Xcode Command-Line Tools: Homebrew demands to install the Xcode command-line tool from Apple's Xcode before using it. To install Xcode, you have to run the following command in your macOS Terminal:  xcode-select --install Homebrew package manager: By default, macOS does not incorporate the Homebrew package. You can install Homebrew using the documentation given on their official website (https://brew.sh/#install).  Hardware Requirement:Intel Processor / Apple M1 Processor 4 GB RAM preferred Installation StepsInstall Manually without BrewStep 1: Let us now download MongoDB. For this, open your web browser and type: google.comStep 2: From Google search, type: MongoDB and hopefully, the first link the search throws up would be the MongoDB link. From here, we have two ways of installing MongoDB. Follow these steps to install using the macOS terminal.Step 3: Go to mongodb-community Select the version, platform, and package. Make sure you choose macOS as the platform and 'tgz' as the file format and click the download button.Step 4: Once the tgz file gets downloaded, go to the macOS terminal to extract it. Step 5: Mostly, your MongoDB will get downloaded in the Downloads folder. For this, type the following command in the terminal:cd Downloads/ ls tar xzf mongodb-osx-ssl-x86_64-4.4.tgz Step 6: Now, we have to move the MongoDB folder to our local binary storage. sudo mv mongodb-osx-ssl-x86_64-4.4 /usr/local/mongodbThis will ask for your system password. Provide the password. You can change the directory to /usr/local/mongodb and see whether all the files exist or not using the ls command. Note that this step is optional. To change the directory, type the command cd /usr/local/mongodb Next, you have to create the db folder. By default, MongoDB writes or stores the data in the folder called data/db. The command for this will be sudo mkdir -p /data/db The -p flag will allow us to create the directory structure. Now, to check whether this path and directory have been created or not, we use the command: cd /data/dbTo check whether we are on the right directory or not, just type the command: pwdFor changing the permission, you need to know your username first. To know your username, type the command: whoamiNow change the permission of this directory. To do this, the command is: sudo chown /data/db Finally, you are eligible to directly run the mongo process.  Install using Brew –If you want to install MongoDB through Homebrew manually, follow these steps – Step 1: Homebrew helps in installing and managing applications on MacOS. If you haven't downloaded or installed Homebrew, then click the link (https://github.com/mongodb/homebrew-brew) to download the official Homebrew formula for MongoDB, by running the command in your macOS Terminal:  brew update  brew tap mongodb/brew Step 2: Once the Homebrew package resides in your system, you can download MongoDB using brew. Step 3: Type the following command in your macOS Terminal: brew install mongodb-community@version-numberStep 4: This installation will add the following binaries: The mongod server The mongo shell The mongos sharded cluster query router Step 5: The installation will take a few seconds. Once done, you can create a directory to store MongoDB data using the following command. sudo mkdir -p /data/db Step 6: Now, you have to note that your data directory should have the appropriate permissions. To do this, execute the command: sudo chown -R `id -un` /data/db Step 7: This will ensure that the data directory is ready and has all the proper permissions. Step 8: Apart from that, the MongoDB installation will produce the following files and directories at the locations given below – Intel Processors Apple M1  Log directory/usr/local/var/log/mongodb/opt/homebrew/var/log/mongodbConfiguration file/usr/local/etc/mongod.conf/opt/homebrew/etc/mongod.confData directory/usr/local/var/mongodb/opt/homebrew/var/mongodbStep 9: Let us now run the MongoDB community Edition. You can use the brew command to run MongoDB as a macOS. A manual procedure is needed to run MongoDB services on macOS. To execute MongoDB daemon, which resides by the name mongod (process), use the following command: brew services start mongodb-community macOS will run this process as a macOS service. Step 10: For stopping a mongod process running as a macOS service, apply the following command: brew services stop mongodb-communityStep 11: For running MongoDB in the background manually and listening for connections on a given port, use the following command - For Mac systems with Intel processors: mongod --config /usr/local/etc/mongod.conf --fork For Mac systems with Apple M1 processors: mongod --config /opt/homebrew/etc/mongod.conf –fork Step 12: Next, verify your MongoDB version. To do this, type the following command: mongo –version Step 13: The command line will display the installed version of MongoDB on your Mac system. Developers recommend using the newest version of libraries and software whenever feasible. It will keep you away from any compatibility issues with client-side applications. Step14: You can view the installation list by typing the command: mongodb Step15: Use the command mongod --config /usr/local/etc/mongod.conf to start the MongoDB Step 16: To connect to mongodb service, type the command: mongo Step17: Use the ‘show dbs’ command to see all databases. You can learn more about the working of MongoDB and become an expert NoSQL database administrator by joining the course https://www.knowledgehut.com/web-development/mongodb-administrator. This course covers features of MongoDB 4.0 and future releases. Uninstall MongoDB on macOS X –Uninstalling MongoDB from your system will entirely remove MongoDB along with its associated files. Before uninstalling MongoDB, check whether any mongo service is running by using the command: launchctl list | grep mongo If any running process exists before uninstallation, you should stop or kill it. To kill all the processes related to mongod, use the command: pkill -f mongod The command to uninstall MongoDB from your system is: If installed via brew: brew uninstall mongodb-communityOr, if installed manually you can simply delete the folder: rm -rf If you have a separate folder for the database, use the command to remove that database directory: rm -rf /data/db MongoDB is the leading NoSQL, document-based, open-source database system. It is a cross-platform system - licensed under the Server-Side Public License (SSPL). Due to its broad spectrum of features and benefits, it became popular very quickly. Hopefully, this article has helped you understand the basics of installing MongoDB in your Apple system.   In this article, we have walked you through the two ways to install MongoDB in a macOS. Also, this article explicitly talked about installing MongoDB in Apple systems with Intel processors and with Apple M1 processors. So, you can navigate this article as per your system. You can learn more about MongoDB installation and join the course from https://www.knowledgehut.com/web-development/mongodb-administrator.
How to Install MongoDB on a Mac

MongoDB is one of the most popular unstructured da... Read More