https://angular.io/guide/setup-local
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { AddComponent } from './add/add.component';
import { HomeComponent } from './home/home.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http'
@NgModule({
declarations: [
AppComponent,
AddComponent,
HomeComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routing.module.ts
if app-routing.module.ts is not present then run this in root folder
ng generate module app-routing –flat –module=app
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AddComponent } from './add/add.component';
const routes: Routes = [
{ path: 'add', component: AddComponent },
{ path: 'add/:num1/:num2', component: AddComponent },
// { path: 'sub', component: SubComponent },
// { path: 'mul', component: MulComponent },
// { path: 'div', component: DivComponent },
{ path: '**', component: HomeComponent },
];
@NgModule({
declarations: [],
imports: [
CommonModule,
RouterModule.forRoot(routes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }
app.component.html
<a routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">Home</a> |
<a routerLink="/add" routerLinkActive="active">Add</a>
<router-outlet></router-outlet>
app.component.css
.active {
background-color: beige;
}
home.component.ts
ng g c home
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms'
import { HomeService } from './home.service'
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
fruits = ["Orange", "Mango", "Banana", "Apple"];
num1: number = 0;
square: number = 0;
form = new FormGroup({
num1: new FormControl(),
num2: new FormControl()
});
formResult: any;
userRecords: any;
constructor(private service: HomeService) { }
ngOnInit() {
}
getSqr() {
var x = this.num1;
this.square = x * x;
}
addNum() {
let x = parseInt(this.form.value.num1);
let y = parseInt(this.form.value.num2);
this.formResult = x + y;
}
getUsers() {
this.service.getData().subscribe((response) => {
console.log(response);
this.userRecords = response;
})
}
}
home.component.html
<p>home works!</p>
{{ fruits }}
<div *ngFor="let fruit of fruits">
{{fruit}}
</div>
<input type="text" (keyup)="getSqr()" [(ngModel)]="num1"/>
<div>
Square of {{num1}} is {{square}}
</div>
<form [formGroup]="form" (submit)="addNum()">
<input type="text" formControlName="num1"/>
<input type="text" formControlName="num2"/>
{{ form.value | json }}
<div>
Result: {{ formResult }}
</div>
<input type="submit" value="Add"/>
</form>
<button (click)="getUsers()">Get Data from Json Placeholder</button>
<div>
{{userRecords}}
<pre>
{{userRecords | json}}
</pre>
</div>
home.service.ts
cd home
ng g s home
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class HomeService {
constructor(private http: HttpClient) { }
getData() {
let url = "https://jsonplaceholder.typicode.com/users";
return this.http.get(url);
}
}
add.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
selector: 'app-add',
templateUrl: './add.component.html',
styleUrls: ['./add.component.css']
})
export class AddComponent implements OnInit {
number: number;
param1: number;
param2: number;
constructor(private route: ActivatedRoute, private router: Router) {
console.log(this.route.snapshot.url)
console.log(this.route.snapshot.params)
this.number = parseInt(this.route.snapshot.queryParamMap.get('id'))
this.param1 = parseInt(this.route.snapshot.params.num1);
this.param2 = parseInt(this.route.snapshot.params.num2);
}
ngOnInit() {
console.log(this.number)
console.log(this.param1)
console.log(this.param2)
// setTimeout(() => {
// this.router.navigate(['home']);
// }, 3000)
}
}
my-app\src\app\interceptor\httpconfig.interceptor.ts
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpResponse,
HttpHandler,
HttpEvent,
HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
@Injectable()
export class HttpConfigInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token: any = localStorage.getItem('token');
// const token: string = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1X25hbWUiOiJhZG1pbiIsInB3ZCI6IkBkbWluIiwiaWF0IjoxNjEyNjM2OTc5fQ.ehlxu7z_1HSW4bPK902nLOAZOpHtutfkJ43lCxQnL68`;
if (token) {
request = request.clone({ headers: request.headers.set('Authorization', 'Bearer ' + token) });
}
if (!request.headers.has('Content-Type')) {
request = request.clone({ headers: request.headers.set('Content-Type', 'application/json') });
}
request = request.clone({ headers: request.headers.set('Accept', 'application/json') });
return next.handle(request).pipe(
map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
console.log('event--->>>', event);
}
return event;
}));
}
}
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { RouterModule } from '@angular/router';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'
import { HttpConfigInterceptor } from './interceptor/httpconfig.interceptor';
@NgModule({
declarations: [
AppComponent,
],
imports: [
HttpClientModule
],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: HttpConfigInterceptor, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule { }