Friday, 24 November 2017

Number, String and Array method in Typescript/JavaScript

String Methods in JavaScript/TypeScript
A list of the methods available in String object along with their description is given below –

S.No.
Method & Description
1.
Returns the character at the specified index.
2.
Returns a number indicating the Unicode value of the character at the given index.
3.
Combines the text of two strings and returns a new string.
4.
Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.
5.
Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.
6.
Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
7.
match()
Used to match a regular expression against a string.
8.
Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.
9.
Executes the search for a match between a regular expression and a specified string.
10.
Extracts a section of a string and returns a new string.
11.
Splits a String object into an array of strings by separating the string into substrings.
12.
Returns the characters in a string beginning at the specified location through the specified number of characters.
13.
Returns the characters in a string between two indexes into the string.
14.
The characters within a string are converted to lower case while respecting the current locale.
15.
The characters within a string are converted to upper case while respecting the current locale.
16.
Returns the calling string value converted to lower case.
17.
Returns a string representing the specified object.
18.
Returns the calling string value converted to uppercase.
19.
Returns the primitive value of the specified object.

Number Methods in JavaScript/TypeScript
The Number object contains only the default methods that are a part of every object's definition. Some of the commonly used methods are listed below –

S.No.
Methods & Description
1.
Forces a number to display in exponential notation, even if the number is in the range in which JavaScript normally uses standard notation.
2.
Formats a number with a specific number of digits to the right of the decimal.
3.
Returns a string value version of the current number in a format that may vary according to a browser's local settings.
4.
Defines how many total digits (including digits to the left and right of the decimal) to display of a number. A negative precision will throw an error.
5.
Returns the string representation of the number's value. The function is passed the radix, an integer between 2 and 36 specifying the base to use for representing numeric values.
6.
Returns the number's primitive value.


Array Methods in JavaScript/TypeScript
 A list of the methods of the Array object along with their description is given below.

S.No.
Method & Description
1.
Returns a new array comprised of this array joined with other array(s) and/or value(s).
2.
Returns true if every element in this array satisfies the provided testing function.
3.
Creates a new array with all of the elements of this array for which the provided filtering function returns true.
4.
Calls a function for each element in the array.
5.
Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
6.
Joins all elements of an array into a string.
7.
Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
8.
Creates a new array with the results of calling a provided function on every element in this array.
9.
Removes the last element from an array and returns that element.
10.
Adds one or more elements to the end of an array and returns the new length of the array.
11.
Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.
12.
Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.
13.
Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.
14.
Removes the first element from an array and returns that element.
15.
Extracts a section of an array and returns a new array.
16.
Returns true if at least one element in this array satisfies the provided testing function.
17.
Sorts the elements of an array.
18.
Adds and/or removes elements from an array.
19.
Returns a string representing the array and its elements.
20.
Adds one or more elements to the front of an array and returns the new length of the array.




Wednesday, 22 November 2017

In Angular2 *ngFor iteration, how do I output only unique values from the array?




1. Create a custome pipe

import { Pipe, PipeTransform } from '@angular/core';
import * as _ from 'lodash';

@Pipe({
name: 'unique',
pure: false
})

export class UniquePipe implements PipeTransform {
transform(value: any): any{
if(value!== undefined && value!== null){
return _.uniqBy(value, 'name');
}
return value;
}
}


2. Use In ngFor


<ul>
<li *ngFor="let datum of data | unique">
{{datum.name}}
</li>
</ul>



3. Import this pipe into module.


import {NgModule, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
import {UniquePipe } from '../shared/pipes/uniqe.pipe.ts';
@NgModule({
imports: [NgbModule.forRoot()],
declarations: [ ItemsListComponent, UniquePipe ]
})
export class MainModule {
}






Monday, 20 November 2017

Apply loader in angular 4 using shared service and component.



1. Create a shared service and Import "Subject" from 'rxjs/Subject' like this=>


import { Injectable } from '@angular/core';
import {Subject} from 'rxjs/Subject';

@Injectable()
export class PreloaderService {

showLoaderFull: Subject<boolean> = new Subject<true>();
showLoaderSmall: Subject<boolean> = new Subject<true>();

getShowLoader() {
return this.showLoaderFull.asObservable();
}
showPreloader(preloaderType = 'full'): void {
if (preloaderType === 'full') {
this.showLoaderFull.next(true);
} else if (preloaderType === 'small') {
this.showLoaderSmall.next(true)
}
}
hidePreloader(preloaderType = 'full'): void {
if (preloaderType === 'full') {
this.showLoaderFull.next(false);
} else if (preloaderType === 'small') {
this.showLoaderSmall.next(false);
}
}
}



2. Create a Component and call this shared service in the same component like this=>


import { Component } from '@angular/core';
import {PreloaderService} from '../../../services/preloader.service';

@Component({
selector: 'preloader',
styleUrls: ['preloader.component.css'],
templateUrl: './preloader.component.html'
})
export class PreloaderComponent {
showloader = false;
constructor(public preloaderService: PreloaderService) {
preloaderService.getShowLoader().subscribe(
res =>this.showloader = res)
}
}

3. Create an Html for loader like this or what you want =>


<div class="preloader-full" *ngIf="showloader">
<svg class="circular" viewBox="25 25 50 50">
<circle class="path" cx="50" cy="50" r="20" fill="none"
stroke-width="2" stroke-miterlimit="10" />
</svg>
</div>


4. Show a loader(call this shared service in the component) like this=>


import { Component } from '@angular/core';
import {PreloaderService} from '../../../services/preloader.service';

@Component({
selector: 'preloader',
styleUrls: ['preloader.component.css'],
templateUrl: './preloader.component.html'
})
export class ShowloaderComponent {
constructor(public preloaderService: PreloaderService) {
preloaderService.showPreloader();
}
}


5. Hide a loader(call this shared service in the component) like this =>



import { Component } from '@angular/core';
import {PreloaderService} from '../../../services/preloader.service';

@Component({
selector: '..selectorname',
styleUrls: ['....css'],
templateUrl: '....html'
})
export class HideloaderComponent {
constructor(public preloaderService: PreloaderService) {
preloaderService.hidePreloader();
}
}










Monday, 30 October 2017

Call parent to child or child to parent method(Pass value one component to another (Next or Prev))



1. Parent component TS file
======================
import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { ChildComponent } from './ChildComponent.ts';
@Component({
templateUrl: './parent.component.html',
})
export class ParentComponent implements OnInit {
@ViewChild(ChildComponent) child;
order: any;
title: any;
isPrevDisabled: boolean = false;
isNextDisabled: boolean = false;
totalOrderID: any;
lastorder: any;

constructor()
{
this.sfdcId = 1;
this.title = "Parent Header";
}

ngOnInit() {
/*
*Get last order id in this method
*/
this.purchaseOrderApi.findOne({"order": "id DESC",fields: { id: true }}).subscribe(lastorder => {
this.lastorder = lastorder
this.totalOrderID = this.lastorder.id;
}, error => { console.log(error.message) });
}
/*
* Enable or disabled next or previous button.
* Change Page Title
*/
public GetOrder(reqObj: any): void {
if(reqObj)
{
this.title=reqObj.Job_orderId;
const currentOrderId=reqObj.Current_orderId;
if (this.totalOrderID < currentOrderId + 1) {
this.isNextDisabled = true;
this.isPrevDisabled = false;
}
else if (currentOrderId - 1 <= 0) {
this.isNextDisabled = false;
this.isPrevDisabled = true;
}
else
{
this.isNextDisabled = false;
this.isPrevDisabled = false;
}
}
}

prevclick() {
this.child.getPrevOrder();

}
nextclick() {
this.child.getnextOrder();
}

}




2. Parent component HTML file 
======================
parent.component.html

<div class="col-sm-12 col-md-6 text-right">
<div>
<button (click)="prevclick()"
disabled]="isPrevDisabled"
type="button">&laquo; Back
</button>
<button (click)="nextclick()"
[disabled]="isNextDisabled"
type="button">Next &raquo;
</button>
</div>
</div>
<div>
<child-detail modelName='order' modelId={{sfdcId}}
(GetcurrentOrder)="GetOrder($event)">
</child-detail>
</div>

3. Child component TS file
=====================
import { Component, OnInit, Input,Output, EventEmitter } from '@angular/core';
import { PurchaseOrderApi } from '../sdk/services/custom/PurchaseOrder';

@Component({
selector: 'child-detail',
templateUrl: './child-detail.component.html'
})
export class ChildComponent implements OnInit {
@Input() modelName: string;
@Input() modelId: string;
@Output() GetcurrentOrder: EventEmitter<any>
= new EventEmitter<any>();

order: any;
currentOrderId: number;
relationsearchArray:any;

constructor(private purchaseOrderApi: PurchaseOrderApi) {

this.relationsearchArray = [{ relation: 'vendor', scope: { fields: { Name: true } } },
{ relation: 'jobsite', scope: { fields: { Name: true } } }]
}
ngOnInit() {
console.log('Call made for model ' + this.modelName);
this.getOrderDetails({ 'sfdcId': this.modelId });
}

getOrderDetails(query: any) {
this.purchaseOrderApi.findOne({include: this.relationsearchArray,'where': query }).subscribe(order => {
this.order = order
this.currentOrderId = this.order.id;
const reqObj={Current_orderId:this.currentOrderId,
Job_orderId:this.order.sfdcId};

this.GetcurrentOrder.emit(reqObj);
},
error => { console.log(error.message) });
}

getPrevOrder()
{
this.getOrderDetails({ 'id': this.currentOrderId-1 })
}

getnextOrder()
{
this.getOrderDetails({ 'id': this.currentOrderId+1 })
}
}




4. Child component HTML file
======================

<div class="col-sm-6">
<strong class="text-muted">Vender Name</strong>
<p>{{order?.vendor?.Name}}&nbsp;</p>
</div>
<div class="col-sm-6">
<strong class="text-muted">Job Order ID</strong>
<p>{{order?.Work_Order_num__c}}&nbsp;</p>
</div>

Sunday, 15 October 2017

Browser refresh doesn't work on any of the URLs in angular

I have worked on this issue and I have found the solution:

Angular supports two Location Strategies:

  1. HashLocationStrategy (e.g  http://localhost:4200/#/product)
  2. PathLocationStrategy (e.g http://localhost:4200/product)

Right now we are using PathLoaction Strategy and this is totally based on server side routing. In this strategy, Hosting server must support for HTML5 based routing.

In our case, when we click on refresh button or type URL http://localhost:4200/product, The browser will send the request to the web server. Since the page “product” does not exist, it will return the 404 error.
This problem could be solved, if we are able to redirect all the request to the index.html

For testing purpose, I have deployed our application into our local IIS server and rewrite a rule in IIS server web config file and this problem has been fixed.


<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.webServer> 
        <rewrite>
            <rules>
                <rule name="redirect all" stopProcessing="true">
                    <match url="^(.*)$" ignoreCase="false" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" pattern="" ignoreCase="false" />
                    </conditions>
                    <action type="Rewrite" url="index.HTML" appendQueryString="true" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>



Please check it and update config file on the server, This problem should be fixed.