วันศุกร์ที่ 10 มกราคม พ.ศ. 2563

Angular 8 - เรียกข้อมูลแบบ JSON ผ่าน HTTPClient

เตรียมข้อมูล JSON ชื่อ shipping.json ใน Folder assets แล้วทดสอบเรียกผ่าน URL : "http://localhost:4200/assets/shipping.json"
src/assets/shipping.json
1
2
3
4
5
6
7
8
9
10
11
12
[
    {
        "type": "Overnight",
        "price": "25.99"
    },{
        "type": "2-Day",
        "price": "9.99"
    },{
        "type": "Postal",
        "price": "2.99"
    }
]

เพิ่ม HttpClientModule ที่ไฟล์ app.module.ts
src/app/app.module.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
 
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
 
import { RouterModule } from '@angular/router';
 
import { TopBarComponent } from './top-bar/top-bar.component';
import { ProductListComponent } from './product-list/product-list.component';
import { ProductAlertsComponent } from './product-alerts/product-alerts.component';
import { ProductDetailComponent } from './product-detail/product-detail.component';
import { CartComponent } from './cart/cart.component';
 
 
@NgModule({
  declarations: [
    AppComponent,
    TopBarComponent,
    ProductListComponent,
    ProductAlertsComponent,
    ProductDetailComponent,
    CartComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    AppRoutingModule,
    RouterModule.forRoot([
      { path: '', component: ProductListComponent },
      { path: 'product/:productId', component: ProductDetailComponent },
      { path: 'cart', component: CartComponent}
    ]),
  ],
  providers: [],
  bootstrap: [AppComponent]
})
 
export class AppModule { }

ทำการ Import HttpClient และเพิ่ม http ใน Constructor แล้วเรียกใช้ด้วยคำสั่ง http.get('*.json') ใน Cart Service "cart.component.ts"
src/app/cart.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import { Injectable } from '@angular/core';
 
import { HttpClient } from '@angular/common/http';
 
@Injectable({
  providedIn: 'root'
})
 
export class CartService {
 
  items = [];
 
  constructor(private http: HttpClient) { }
 
  addItem(product) {
    this.items.push(product);
  }
 
  getItems() {
    return this.items;
  }
 
  clearItems() {
    this.items = [];
  }
 
  getShippingPrices() {
    return this.http.get('/assets/shipping.json');
  }
   
}

เพิ่มคำสั่งเรียกข้อมูลผ่าน cartService ใน Method ngOnInit แล้วเก็บไว้ที่ shippingPrices
เสร็จแล้วเพิ่มใน Template ให้แสดงผล อย่าลืมเพิ่ม | async ด้วย
src/app/cart/cart.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { Component, OnInit } from '@angular/core';
 
import { CartService } from '../cart.service';
 
@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.css']
})
 
export class CartComponent implements OnInit {
 
  items;
  shippingPrices;
 
  constructor(private cartService: CartService) { }
 
  ngOnInit() {
    this.items = this.cartService.getItems();
    this.shippingPrices = this.cartService.getShippingPrices();
     
    this.shippingPrices.subscribe((data) => {
      window.console.log(data);
    });
     
  }
 
}
src/app/cart/cart.component.html
1
2
3
4
5
6
7
8
9
10
11
<h1>Cart</h1>
 
<div class="cart-item" *ngFor="let item of items; index as itemId">
    <span>{{item.name}}</span>
    <span>{{item.price || currency }}</span>
</div>
 
<div class="shipping-item" *ngFor="let shippingPrice of shippingPrices | async">
    <span>{{shippingPrice.type}}</span>
    <span>{{shippingPrice.price}}</span>
</div>



หากเราต้องการนำข้อมูลมาประมวลผลเองให้เราใช้ subscribe ในการดึงข้อมูลออกมาใช้ ตัวอย่าง Output ให้ดูที่ Console ด้านซ้ายมือ
การใช้งานเพิ่มเติมอ่านได้ที่ https://angular.io/guide/http
src/app/cart/cart.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { Component, OnInit } from '@angular/core';
 
import { CartService } from '../cart.service';
 
@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.css']
})
 
export class CartComponent implements OnInit {
 
  items;
  shippingPrices;
 
  constructor(private cartService: CartService) { }
 
  ngOnInit() {
    this.items = this.cartService.getItems();
    this.shippingPrices = this.cartService.getShippingPrices();
     
    this.shippingPrices.subscribe((data) => {
      window.console.log(data);
    });
     
  }
 
}

ไม่มีความคิดเห็น:

แสดงความคิดเห็น