Skip to main content

Angular

API FORMAT : host/project_dir/controller_name/method_name?param1=&param2=&param2=&param2=

=============== Angular ==================
 The ng-app directive tells AngularJS that this is the root element of the AngularJS application. All AngularJS applications must have a root element. You can only have one ng-app directive in your HTML document. If more than one ng-app directive appears, the first appearance will be used.

An NgModule is a class marked by the @NgModule decorator. @NgModule takes a metadata object that describes how to compile a component's template and how to create an injector at runtime.


JSON.parse() is for "parsing" something that was received as JSON.
JSON.stringify() is to create a JSON string out of an object/array.
They are the inverse of each other.
JSON.stringify() serializes a JS object into a JSON string, whereas JSON.parse() will deserialize a JSON string into a JS object.

URL : https://angular.io/cli
===============================
Angular 4 installations

 npm install -g @angular/cli

 ng new myangularapp

 cd myangularapp

 ng serve

 ng serve --host=192.168.1.105
==================================

ng help
ng generate --help
ng new my-first-project
cd my-first-project
ng serve

The ng new command creates an Angular workspace folder and generates a new app skeleton. A workspace can contain multiple apps and libraries. The initial app created by the ng new command is at the top level of the workspace. When you generate an additional app or library in a workspace, it goes into a projects/ subfolder.

ng commandNameOrAlias requiredArg [optionalArg] [options]
ng build my-app -c production

The page you see is the application shell. The shell is controlled by an Angular component named AppComponent.
Components are the fundamental building blocks of Angular applications. They display data on the screen, listen for user input, and take action based on that input.

the implementation of the shell AppComponent distributed over three files:

  *  app.component.ts— the component class code, written in TypeScript.
  *  app.component.html— the component template, written in HTML.
  *  app.component.css— the component's private CSS styles.

=====================
* Using the Angular CLI, generate a new component named heroes.

ng generate component heroes

===============
src/app/app.component.html
<h1>Angular Router</h1>
<nav>
  <a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a>
  <a routerLink="/heroes" routerLinkActive="active">Heroes</a>
</nav>
<router-outlet></router-outlet>

======================
Testing ports :
1337,1859,3000,3002,3030,3128,3306,3333,3621,4000,4502,5000,5757,5790,
7774,8000,8001,8080,8081,8082,8083,8084,8085,8086,8443,8760,8888,8899,
Any port between 9000 and 9100
Any port between 9200 and 9400
9876,9877,9880,Any port between 9900 and 9999
10002,13260,14357,38946,49772,0208,54134,54136,60778,63342,64000

=========================
Create a form component

> app.module.ts
import { FormsModule }   from '@angular/forms';

@NgModule({
  imports: [
    FormsModule
  ],

Two-way data binding with ngModel

> ng generate class Hero

-- hero.ts
export class Hero {

  constructor( public name: string ) { }
}

-- page.ts
import { Hero } from '../hero';

export class HeroComponent {

  model = new Hero();

  ngOnInit() {
    return JSON.stringify(this.model);
  }

}
-- page.html
<form #heroForm="ngForm">

<input type="text" class="form-control"
       required
       [(ngModel)]="model.name" name="name">
TODO: remove this: {{model.name}}


<button type="button" name="button" (click)="formdata()">Submit</button>
</form>

=======================================
Form Submission

-- page.html
<form #userlogin = "ngForm" (ngSubmit) = "onClickSubmit(userlogin.value)" >
   <input type = "text" name = "emailid" placeholder = "emailid" ngModel>
   <br/>
   <input type = "password" name = "passwd" placeholder = "passwd" ngModel>
   <br/>
   <input type = "submit" value = "submit">
</form>

--- page.ts
import { FormGroup, FormControl } from '@angular/forms';

export class page  {
  onClickSubmit(data) {
        console.log("Entered data : " + JSON.stringify(data));
     }
}

-- app.module.ts
import { FormsModule } from '@angular/forms';

imports: [
    FormsModule
  ]

========================================
> Module material not found : npm install --save @angular/material

https://java2practice.com/2017/11/03/angular-4-service-example/


http://localhost/vinay/CodeIgniter-API-Controller-master/api_test/getallusers

http://localhost/vinay/CodeIgniterApi/myservice/signup?name=&mobile=&email=&password=
========================================
Working through Service Provider

run > ng g service myservice

++++++++++++ app.module.ts

import { HttpClientModule } from '@angular/common/http';
@NgModule({

  imports: [
    HttpClientModule 
  ],
})

++++++++++++ Pageprovider.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class PageproviderService {
apiUrl = 'http://host/Project/controller/method';
constructor(private http: HttpClient) {  }
   returndata()
   {   
      return this.http.get(this.apiUrl);
   }
}

++++++++++++ Page.component.ts

import { PageproviderService } from '../pageprovider.service';

export class PageComponent  {
  constructor(public pageprovider: PageproviderService){  }
  showdata()
  {
    this.pageprovider.loaddata().subscribe((result) => { console.log('Result:',result);
    },
    (error: any) => {
    console.log('error in this method');
    });
  }
}
===========================================================================
Page Redirection through Method

After you check e-mail and passwork try:
router.navigate(['/show_alunos'])
And in constructor declare

And import { Router } from "@angular/router";
constructor ( private router: Router)
UPDATED:
Simple example how to user Ruter:

your.component.html:
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
  <input type="text" formControlName="Email">
  <input type="password" formContolName="Password">
  <input type="submit" value="login">
</form>

your.component.ts:
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from "@angular/forms";
import { Router } from "@angular/router";

@Component({
  selector: 'component-tag-name',
  templateUrl: './your.component.html'
})

export class YourComponentName implements OnInit {

myForm: FormGroup;
constructor(private router: Router) {}

ngOnInit(){
 this.myForm = this.FormGroup({
   'Email': new FormConrol(null, [Validators.required]),
   'Password': new FormControl(null, [Validators.required])
  })
}

onSubmit(){
  let email = this.myForm.get('Email').value;
  let password = this.myForm.get('Password').value;

  if (email === 'your value' && password === 'your value'){
    this.router.navigate(['/show_alunos']);
  } 
}

In yout app.module.ts you need import this component and ListAlunosComponent too. Then you need import this components and write in your routing config .ts file:
{ path: 'show_alunos', component: ListAlunosComponent }
=========================================================================================
localStorage vs sessionStorage (URL : https://alligator.io/js/introduction-localstorage-sessionstorage/)

localStorage and sessionStorage accomplish the exact same thing and have the same API, but with sessionStorage the data is persisted only until the window or tab is closed, while with localStorage the data is persisted until the user manually clears the browser cache or until your web app clears the data. The examples in this post are for localStorage, but the same syntax works for sessionStorage.

Create key/value pair entries with localStorage.setItem, providing a key and a value:
let key = 'Item 1';
localStorage.setItem(key, 'Value');

Read entries with localStorage.getItem:
let myItem = localStorage.getItem(key);

Update an entry just as you would create a new one with setItem, but with a key that already exists:
localStorage.setItem(key, 'New Value');

Delete an entry with the removeItem method:
localStorage.removeItem(key);

clear everything that’s stored in localStorage:
localStorage.clear();

Only strings can be stored with localStorage or sessionStorage, but you can use JSON.stringify to store more complex objects and JSON.parse to read them:

// Create item:
let myObj = { name: 'Skip', breed: 'Labrador' };
localStorage.setItem(key, JSON.stringify(myObj));

// Read item:
let item = JSON.parse(localStorage.getItem(key));

test for the presence of items in the loclaStorage:

if (localStorage.length > 0) {
  // We have items
} else {
  // No items
}

Test for localStorage support by checking if it’s available on the window object:
if (window.localStorage) {
  // localStorage supported
}

localStorage or sessionStorage don’t have a forEach method, but you can iterate over the items with a good old for loop:

for (let i = 0; i < localStorage.length; i++){
  let key = localStorage.key(i);
  let value = localStorage.getItem(key);
  console.log(key, value);
}
=================================================================================
FLOW OF STORAGE ON PAGES

++++++++ login.ts

import { Router } from "@angular/router";

constructor(private router: Router) {
    if(localStorage.getItem('userToken')!==null){
      console.log("Storage not empty");
      this.router.navigate(["/dashboard"]);
    }

login(user){

 this.authprovider.checklogin(user).subscribe((result) => {
 if(result){ localStorage.setItem('userToken',JSON.stringify(result[0].id));
 this.router.navigate(['/dashboard']); } else { this.router.navigate(["/home"]); }
 },
 (error: any) => {  console.log('error in Login method');  });
 }

}
+++++++ dashboard.ts
import { Router } from "@angular/router";

userid : any;
name : string;
constructor(private router: Router, public authprovider: AuthproviderService) {

    if(localStorage.getItem('userToken')==null){
      console.log("Empty strorage");
      this.router.navigate(["/login"]);
    }
}
ngOnInit() {
   this.userid = localStorage.getItem('userToken');
   this.authprovider.userinfo(this.userid).subscribe((result) => { 
    this.name = result[0].name;
   },
    (error: any) => {
        console.log('DETAIL ERROR');
    });
}

logout() { 
    localStorage.removeItem('userToken');
    localStorage.clear();
    this.router.navigate(["/home"]);
}

========================================================================
https://www.agiratech.com/angular-4-template-driven-forms-building-validating/

========================================================================
Passing Complex Data Through The Angular Router With NativeScript

https://www.thepolyglotdeveloper.com/2016/10/passing-complex-data-angular-2-router-nativescript/

https://stackoverflow.com/questions/44864303/send-data-through-routing-paths-in-angular

+++++++++++++++++++++

<h1>Angular 4: Template-driven forms</h1>
<form #validateForm="ngForm" (ngSubmit)="register(validateForm)" countryCity telephoneNumbers novalidate>
  <p> Is "validateForm" valid? {{(validateForm.valid?'Yes':'No')}} </p>

  <div>
    <label>Name</label>
    <input type="text" name="name" #name="ngModel" ngModel required>
    <errors [control]="name"></errors>
  </div>
  <div>
    <label>Email</label>
    <input type="text" name="email" #email="ngModel" ngModel required email-validate>
    <errors [control]="email"></errors>
  </div>
  <div>
    <label>Age</label>
    <input type="number" name="age" #age="ngModel" ngModel required age-validate>
    <errors [control]="age"></errors>
  </div>

  <div ngModelGroup="address">
    <h3>Address</h3>
    <div>
      <label>Country</label>
      <input type="text" name="country" #country="ngModel" ngModel required minlength="5" maxlength="30">
      <errors [control]="country"></errors>
    </div>
    <div>
      <label>City</label>
      <input type="text" name="city" ngModel required>
    </div>
  </div>

  <errors [control]="validateForm"></errors>

  <pre>{{validateForm.value | json}}</pre>
  <button type="submit" [disabled]="validateForm.invalid">Submit</button>
</form>
+++++++++++
import { NgForm } from '@angular/forms';
import { Component, ViewChild } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent {

  private count = 1;

  phoneNumberIds: number[] = [1];

  @ViewChild('validateForm')
  private validateForm: NgForm;

  constructor() {
  }


  register(validateForm: NgForm) {
    console.log('Registration successful.');
    console.log(validateForm.value);
    alert("Hi "+validateForm.value.name+" you information are valid.")
  }
}

================================================================
FORM VALIDATION (https://www.toptal.com/angular-js/angular-4-forms-validation)
REACTIVE  FORMS : https://www.concretepage.com/angular-2/angular-2-4-pattern-validation-example

In Angular 4, the following four statuses are commonly used by forms:

    valid – state of the validity of all form controls, true if all controls are valid

    invalid – inverse of valid; true if some control is invalid

    pristine – gives a status about the “cleanness” of the form; true if no control was modified

    dirty – inverse of pristine; true if some control was modified

+++++++++++++++++++++++++++++++++++

    name - is required and unique among all registered users
    birthYear - should be a valid number and the user must have at least 18 and less than 85 years
    country - is mandatory, and just to make things a bit complicated, we need a validation that if the country is France, then the city must be Paris (let’s say that our service is offered only in Paris)
    phoneNumber – each phone number must follow a specified pattern, there must be at least one phone number, and the user is allowed to add a new or remove an existing telephone number.
    The “Register” button is enabled only if all inputs are valid and, once clicked, it submits the form.
    The “Print to Console” just prints the value of all inputs to console when clicked.
 
    Template-driven Forms
    module for the template-driven forms is FormsModule.
<form>  ..
  <input type="text" name="name" ngModel>
  <input type="text" name="birthYear" ngModel >
  <input type="text" name="country" ngModel/>
  <input type="text" name="city" ngModel/>
  <input type="text" name="phoneNumber[1]" ngModel/>
</form>
 
 
    By adding the NgModel directive, all inputs are registered to the NgForm component. 

    Retrieving the values of all registered input controls
    Retrieving the overall state of all controls
 
<form #myForm="ngForm">
 <pre>{{myForm.value | json}}</pre>
</form>
 
    Validation is really important for each application. We always want to validate the user input (we cannot trust the user) to prevent sending/saving invalid data and we must show some meaningful message about the error to properly guide the user to enter valid data.
 
    Angular 4 already offers a set of common validators like: required, maxLength, minLength…
 
    <input name="name" ngModel required maxLength="4" minLength="2"/>
    ------
<form #myForm="ngForm" (ngSubmit)="actionOnSubmit(myForm)" novalidate>
  <p>Is "myForm" valid? {{myForm.valid}}</p>   ..
  <input type="text" name="name" ngModel required/>   ..
  <input type="text" name="birthYear" ngModel required pattern="\\d{4,4}"/>   ..
  <div ngModelGroup="location"> ..
<input type="text" name="country" ngModel required/> ..
<input type="text" name="city" ngModel/>
  </div>
  <div ngModelGroup="phoneNumbers"> ..
<input type="text" name="phoneNumber[{{phoneId}}]" ngModel required/> ..
  </div>   ..
</form>
 
 Note: novalidate is used to disable the browser’s native form validation. 
 
  <form #myForm="ngForm" (ngSubmit)="actionOnSubmit(myForm)" novalidate>
<p>Is "myForm" valid? {{myForm.valid}}</p>
<input type="text" name="name" ngModel required/>
  </form>
  +++++++++++++++++++++

  unamePattern = "^[a-z0-9_-]{8,15}$";
  pwdPattern = "^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).{6,12}$";
  mobnumPattern = "^((\\+91-?)|0)?[0-9]{10}$";
  emailPattern = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$";

===================================================================
 
++++++++login.ts
 import { Router } from "@angular/router";
import { AuthproviderService } from '../authprovider.service';
 
 constructor(public authprovider: AuthproviderService,private router: Router) {}
 
   login(user){
 
   this.authprovider.checklogin(user).subscribe((result) => {

      if(result!==null){
        console.log("Logged id",JSON.parse(result[0].id))
     
        this.router.navigate(['/dashboard']);
      }else{
        console.log("Invalid Params!")
        this.router.navigate(["/home"]);
      }
      },
      (error: any) => {
          console.log('error in Login method');
      });
  }
 
++++++ service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class AuthproviderService {
apiUrl = 'http://192.168.1.105/vinay/CodeIgniterApi/myservice'; // don't remove http://
  constructor(private http: HttpClient) {

  }
   checklogin(user){
     return this.http.get(this.apiUrl+'/signin?name='+user.username+'&password='+user.password);;
   }


======================================================================
FILE UPLOAD WITH PROVIDER

-----------------------
HTML:

<form class="contact-form" #userdata ="ngForm" (ngSubmit) = "register(userdata.value)" enctype="multipart/form-data">
<div class="form-group">
  <input type="text" class="form-control" id="name" name="username" placeholder="Name" minlength="2" pattern="[a-zA-Z ]*" #username="ngModel" required ngModel>
</div>
<div class="form-group">
   <input class="form-control" type="file" (change)="onFileChanged($event)"  required name="fileInput"  ngModel>
</div>
</form>

-----------------------
TS:
import { AuthproviderService } from '../authprovider.service';

export class RegisterComponent  {
selectedFile: File = null ;
  constructor(public authprovider: AuthproviderService)
  {}
  onFileChanged(event) {
    this.selectedFile = <File>event.target.files[0];
  }
  register(data,selectedFile) {

    data = {
        username : data.username,     
        image : this.selectedFile.name,
    };

    const uploadData = new FormData();
    uploadData.append('file', this.selectedFile, this.selectedFile.name);
    this.authprovider.insertimg(uploadData).subscribe((result) => {
    if(result){   
       console.log("upload success");
    }else{
        console.log("upload failed");       
    }

    },
    (error: any) => {
        console.log('error in Upload method');
    });
    }

}
-----------------
PROVIDER :

 import { HttpClient } from '@angular/common/http';

 export class AuthproviderService {

  constructor(private http: HttpClient) { }
  insertimg(uploadData){
     return this.http.post("http://host/project/upload.php",uploadData);
  }
 }
------------------
PHP (upload.php) :

 header('Access-Control-Allow-Origin: *');

 $target_path = "assets/";

 $target_path = $target_path . basename( $_FILES['file']['name']);
 if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
  echo true;
 } else {
  echo false;
 }

=====================================================================
GET ROUTE DATA
*********** 1st page.ts
import { Router} from "@angular/router";
constructor(private router:Router) {
this.router.navigate(['/home',{key : value}]);

}

********* home.ts
import { ActivatedRoute } from "@angular/router";
constructor( private route: ActivatedRoute){

 this.route.params.subscribe(data => {
     console.log("Route DATA",data);
  });
}
###############################################################################
import { Router , ActivatedRoute} from "@angular/router";

  const appRoutes:Routes = [
  {path: '', component: LoginComponent, data:[{PageName:"Login Page"}]}]

Try to filter and loop your events instead of subscribe

constructor(private router:Router, private route: ActivatedRoute) {
    router.events
      .filter(e => e instanceof NavigationEnd)
      .forEach(e => {
        this.title = route.root.firstChild.snapshot.data['PageName'];
    });
}


===========================================================

Comments

  1. sudo apt install nodejs
    node -v
    How to update Node Ubuntu

    curl -sL https://deb.nodesource.com/setup_10.x -o nodesource_setup.sh

    nano nodesource_setup.sh

    sudo bash nodesource_setup.sh

    sudo apt-get install nodejs

    nodejs -v

    ReplyDelete

Post a Comment

Popular posts from this blog

SETUP REST API IN CI

1. Create Rest_controller.php inside controllers and paste code: <?php defined('BASEPATH') OR exit('No direct script access allowed'); require APPPATH . '/libraries/API_Controller.php'; class Rest_controller extends API_Controller { public function __construct() { parent::__construct(); } public function index() { $this->api_return(             [ 'status' => true,                'result' => "Welcome to Testservices."             ],         200); } } ?> 2. Create api.php inside config and paste code : <?php defined('BASEPATH') OR exit('No direct script access allowed'); /**  * API Key Header Name  */ $config['api_key_header_name'] = 'X-API-KEY'; /**  * API Key GET Request Parameter Name  */ $config['api_key_get_name'] = 'key'; /**  * API Key POST Request Parameter Name ...

NGrok Setup

 https://dashboard.ngrok.com/get-started/setup 1. Unzip to install On Linux or Mac OS X you can unzip ngrok from a terminal with the following command. On Windows, just double click ngrok.zip to extract it. unzip /path/to/ngrok.zip 2. Connect your account Running this command will add your authtoken to the default ngrok.yml configuration file. This will grant you access to more features and longer session times. Running tunnels will be listed on the endpoints page of the dashboard. ngrok config add-authtoken 1woFn9zVqcI4VeGuSIiN2VtmnPa_ZXuAuF1AAPkqApr7WVsQ 3. Fire it up Read the documentation on how to use ngrok. Try it out by running it from the command line: ngrok help To start a HTTP tunnel forwarding to your local port 80, run this next: ngrok http 80

API ( service ) Image or Video Upload

## SAVE  VIDEO public function uploadmedia() { $target_path = "assets/uploads/"; $target_path = $target_path . basename($_FILES['file']['name']); if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) { $this->api_return( [ 'status' => true,    'result' => 'uploaded success' ], 200); } else{ $this->api_return( [ 'status' => false,    'result' => 'failed' ], 20); } } ## SAVE FILE IMAGE OR VIDEO public function savefile() { $filetype = $_FILES['file']['type']; if (strpos($filetype, 'image') !== false) { $type = 'image'; } if (strpos($filetype, 'video') !== false) { $type = 'video'; }         $filename = trim($_FILES['file']['name']); // $userid = trim($this->input->get('userid'));...