ANGULAR 2

ANGULAR 2 NOTES:



FILE STRUCTURE














USER INTERFACE PAGES
ANA SEHIFE


HERO DETAIL ( click etdikde acilir bu sehife)

Autoicvomplete search


HEROES LINKI

Hero siyahida her hansi birine click etdikde



INDEX.HTML


<my-app>loading</my-app>
My-app komponenti yuklenene qeder loading sozu gorunecek














APP.MODULE.TS


All modules added to app.modeule.ts

APP.COMPONENT.HTML
<h1>{{title}}</h1>
<nav>
  <a routerLink="/dashboard" routerLinkActive="active">Dashboard</a>
  <a routerLink="/heroes" routerLinkActive="active">Heroes</a>
</nav>
<router-outlet></router-outlet>

APP.COMPONENT.TS
import { Component } from '@angular/core';


@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Tour of Heroes';
}


App-routings.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';


const routes: Routes = [
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' }
];


@NgModule({
imports: [
  RouterModule.forRoot(routes)
],
exports: [
  RouterModule
]
})
export class AppRoutingModule {
}

------------ CORE ( HEROSERVICE  , HEROSERACH SERVICE) --------------
CORE.MODULE.TS
import { NgModule, ModuleWithProviders } from '@angular/core';
import { HttpModule } from '@angular/http';


import { HeroService } from './hero.service';
import { HeroSearchService } from './hero-search.service';


@NgModule({
imports: [
  HttpModule
],
declarations: [],
providers: [
  HeroService,
  HeroSearchService
],
exports: []
})
export class CoreModule {
}





HERO.SERVICE.TS
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';


import 'rxjs/add/operator/toPromise';


import { Hero } from '../shared/hero';


@Injectable()
export class HeroService {


private headers = new Headers({ 'Content-Type': 'application/json' });
private heroesUrl = 'api/heroes';  // URL to web api


constructor(private http: Http) {
}


getHeroes(): Promise<Hero[]> {
  return this.http.get(this.heroesUrl)
      .toPromise()
      .then(response => response.json().data as Hero[])
      .catch(this.handleError);
}


getHero(id: number): Promise<Hero> {
  const url = `${this.heroesUrl}/${id}`;
  return this.http.get(url)
      .toPromise()
      .then(response => response.json().data as Hero)
      .catch(this.handleError);
}


delete(id: number): Promise<void> {
  const url = `${this.heroesUrl}/${id}`;
  return this.http.delete(url, { headers: this.headers })
      .toPromise()
      .then(() => null)
      .catch(this.handleError);
}


create(name: string): Promise<Hero> {
  return this.http
      .post(this.heroesUrl, JSON.stringify({ name: name }), { headers: this.headers })
      .toPromise()
      .then(res => res.json().data as Hero)
      .catch(this.handleError);
}


update(hero: Hero): Promise<Hero> {
  const url = `${this.heroesUrl}/${hero.id}`;
  return this.http
      .put(url, JSON.stringify(hero), { headers: this.headers })
      .toPromise()
      .then(() => hero)
      .catch(this.handleError);
}


private handleError(error: any): Promise<any> {
  console.error('An error occurred', error); // for demo purposes only
  return Promise.reject(error.message || error);
}
}


HERO.SEARCH.SERVICE.TS
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';


import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';


import { Hero } from '../shared/hero';


@Injectable()
export class HeroSearchService {


constructor(private http: Http) {
}


search(term: string): Observable<Hero[]> {
  return this.http
      .get(`api/heroes/?name=${term}`)
      .map(response => response.json().data as Hero[]);
}
}

DASHBOARD.COMPONENT.HTML
<h3>Top Heroes</h3>
<div class="grid grid-pad">
  <a *ngFor="let hero of heroes" [routerLink]="['/detail', hero.id]" class="col-1-4">
      <div class="module hero">
          <h4>{{hero.name}}</h4>
      </div>
  </a>
</div>
<hero-search></hero-search>


Linke click zamani /detail pathine uygun olaraq detail mopdule -a click olunan hero id gonderilir detail gosterilmesi ucun. Detail routingde  id gosterilimelidi routere

DASHBOARD.COMPONENT.TS
import { Component, OnInit } from '@angular/core';


import { Hero } from '../shared/hero';
import { HeroService } from '../core/hero.service';


@Component({
selector: 'my-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
heroes: Hero[] = [];


constructor(private heroService: HeroService) {
}


ngOnInit(): void {
  this.heroService.getHeroes()
      .then(heroes => this.heroes = heroes.slice(1, 5));
}
}

DASHBOARD-ROUTING.MODULE.TS
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';


import { DashboardComponent } from './dashboard.component';


const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent }
];


@NgModule({
imports: [
  RouterModule.forChild(routes)
],
exports: [
  RouterModule
]
})
export class DashboardRoutingModule {}
HERO-DETAIL.COMPONENT.HTML
<div *ngIf="hero">
  <h2>{{hero.name}} details!</h2>
  <div>
      <label>id: </label>{{hero.id}}
  </div>
  <div>
      <label>name: </label>
      <input [(ngModel)]="hero.name" placeholder="name"/>
  </div>
  <button (click)="goBack()">Back</button>
  <button (click)="save()">Save</button>
</div>


HERO-DETAIL.COMPONENT.TS
import 'rxjs/add/operator/switchMap';
import { Component, OnInit }        from '@angular/core';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { Location }                 from '@angular/common';


import { Hero }        from '../shared/hero';
import { HeroService } from '../core/hero.service';


@Component({
selector: 'hero-detail',
templateUrl: './hero-detail.component.html',
styleUrls: [ './hero-detail.component.css' ]
})
export class HeroDetailComponent implements OnInit {
hero: Hero;


constructor(
  private heroService: HeroService,
  private route: ActivatedRoute,
  private location: Location
) {}


ngOnInit(): void {
  this.route.paramMap
    .switchMap((params: ParamMap) => this.heroService.getHero(+params.get('id')))
    .subscribe(hero => this.hero = hero);
}


save(): void {
  this.heroService.update(this.hero)
    .then(() => this.goBack());
}


goBack(): void {
  this.location.back();
}
}

HERO-DETAIL.ROUTING.MODULE.TS
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';


import { HeroDetailComponent } from './hero-detail.component';


const routes: Routes = [
{ path: 'detail/:id', component: HeroDetailComponent }
];


@NgModule({
imports: [
  RouterModule.forChild(routes)
],
exports: [
  RouterModule
]
})
export class HeroDetailRoutingModule {
}


HEROES.COMPONENT.HTML
<h2>My Heroes</h2>
<div>
  <label>Hero name:</label> <input #heroName/>
  <button (click)="add(heroName.value); heroName.value=''">
      Add
  </button>
</div>
<ul class="heroes">
  <li *ngFor="let hero of heroes" (click)="onSelect(hero)"
      [class.selected]="hero === selectedHero">
      <span class="badge">{{hero.id}}</span>
      <span>{{hero.name}}</span>
      <button class="delete"
              (click)="delete(hero); $event.stopPropagation()">x
      </button>
  </li>
</ul>
<div *ngIf="selectedHero">
  <h2>
      {{selectedHero.name | uppercase}} is my hero
  </h2>
  <button (click)="gotoDetail()">View Details</button>
</div>


HEROES.COMPONENTS.TS
  
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';


import { Hero } from '../shared/hero';
import { HeroService } from '../core/hero.service';


@Component({
selector: 'my-heroes',
templateUrl: './heroes.component.html',
styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
heroes: Hero[];
selectedHero: Hero;


constructor(private heroService: HeroService,
            private router: Router) {
}


getHeroes(): void {
  this.heroService
      .getHeroes()
      .then(heroes => this.heroes = heroes);
}


add(name: string): void {
  name = name.trim();
  if (!name) {
    return;
  }
  this.heroService.create(name)
      .then(hero => {
        this.heroes.push(hero);
        this.selectedHero = null;
      });
}


delete(hero: Hero): void {
  this.heroService
      .delete(hero.id)
      .then(() => {
        this.heroes = this.heroes.filter(h => h !== hero);
        if (this.selectedHero === hero) {
          this.selectedHero = null;
        }
      });
}


ngOnInit(): void {
  this.getHeroes();
}


onSelect(hero: Hero): void {
  this.selectedHero = hero;
}


gotoDetail(): void {
  this.router.navigate(['/detail', this.selectedHero.id]);
}
}



Secilen hero selectedhero-ya oturulur/Daha sonra detail view click etdikde gotodetail ile detail pathine id oturulur


SHARED ( classlar , search componenrt)


HERO.TS
export class Hero {
id: number;
name: string;
}


Yorumlar

Bu blogdaki popüler yayınlar

İNGİLİS DİLİNDƏ ƏN ÇOX İSTİFADƏ OLUNAN 2600 CÜMLƏ QƏLİBLƏRİ VƏ 6000 SÖZ

JAVA 8 LAMBDA Expressions AND Stream API - EXAMPLES