Showing posts with label TypeScript. Show all posts
Showing posts with label TypeScript. Show all posts

Monday, April 25, 2022

JSON Path to use in Angular Projects

How to use JSON Path to query any JSON object.

For example, consider below simple JSON, if you want to query JSON we can use simply query as this.obj.name or this.obj.id to access to the JSON

this.obj ={

   id: 1,

   "name": "balaji"

}

For array object we can use index, for ex: this.objData[0].id. For more JSON path to find we can refer https://jsonpathfinder.com/

this.objData = {

        data: [

  {

    "id": 1,

    "name": "Balajiprasad",

    "age": 18,

              "address": {

                      "state": "TN",

                       "country": "India"

                } 

 

  },

  {

    "id": 2,

    "name": "prasad",

    "age": 28,

     "address": {

                      "state": "Tx",

                       "country": "US"

                } 

  }

]}


In angular project, if we need to use JSON path dynamically then we can refer the jsonpath library Ref: https://www.npmjs.com/package/jsonpath

Steps to use,

1. Add "json-path" in package.json file under dependencies

    "dependencies": {

"jsonpath": "1.1.1"

}


2. Add reference of "json-path" directly in component. No need to specify in App.module

    import * as jp from 'jsonpath'

3. Use the JSON path in code , need to use $.. (double dots)

   let state = jp.query(this.objData, '$..data[0].address.state')

 



Monday, July 29, 2019

Angular CLI - Handle Error Globally

To handle error globally in Angular 7 Cli, follow below steps

Ref: https://angular.io/api/core/ErrorHandler

Steps:

- Create ErrorHanlder file as below


import { Injectable, ErrorHandler } from '@angular/core';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  constructor(private ngZone: NgZone) {
  }

  handleError(error) {
    this.ngZone.run(() => {
//use ngZone to attach context to Angular's zone
//custom logic to do anything, for ex: toastService can be injected and shown here
    });

    //log as error to console
    console.error(error);
  }
}



-  Inject GlobalErrorHandler into app.module.ts providers as below


import { NgModule, ErrorHandler } from '@angular/core';
import { GlobalErrorHandler } from './core/config/error.handler';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
  ],
  providers: [
    …,
    { provide: ErrorHandler, useClass: GlobalErrorHandler },
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }


-  Now throw error from anywhere, it will be catched in GlobalErrorHanlder

import { catchError, map } from 'rxjs/operators';

import { Observable, of, throwError } from 'rxjs';
….

getUser(): Observable<User> {
      return this.http.get(this.getUserUrl      )
        .pipe(
        map(response => { return <User>response; }),
        catchError((error, caught) => {
          //handled error globally
          return throwError(error);
        }));

    }

Monday, May 21, 2018

Angular 4 - How to detect device in browser

Its very simple and straight forward to use plugin for Angular 4 typescript as below

Use plugin https://www.npmjs.com/package/ngx-device-detector which can be added to package.json to install as reference

Include in your app.module as below

import { DeviceDetectorModule } from 'ngx-device-detector';


imports: [
      DeviceDetectorModule.forRoot()
    ],

Include in your component or service as below


import { DeviceDetectorService } from 'ngx-device-detector';

constructor(private deviceService: DeviceDetectorService) {   }

To get device info use as below in component

this.deviceService.getDeviceInfo();  //This will get all device useragent info 
this.deviceService.isTablet(); //This will get device is tablet or not
this.deviceService.isDesktop(); //This will get device is desktop or not
this.deviceService.isMobile(); //This will get device is mobile or not