iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 23
1
Modern Web

從零開始的點餐系統,Google好棒棒系列 第 23

[Day23] Angular 主要概念 - http 呼叫

上一篇練習完 router 後,這篇要說明 Angular 內建的 http 呼叫,由於在寫這篇文章的時候,前後端還沒整合好,所以這邊只會介紹 GET 方法,以及透過 http 呼叫拿到 json 檔案。

匯入 HttpClientModule

由於 HttpClientModule 整個專案的會用到,我就把它從 core module 匯入,之後再把 core module 匯入 app module 中,這樣整個專案就可以使用 HttpClientModule 提供的東西了

import { NgModule, Optional, SkipSelf } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [],
  imports: [HttpClientModule],
})
export class CoreModule {
  constructor(@Optional() @SkipSelf() parentModule: CoreModule) {
    if (parentModule) {
      throw new Error(
        'Core is already loaded. Import it in the AppModule only'
      );
    }
  }
}

建立 JSON (暫時) 假數據

在路徑 src/assets 的資料夾中,建立一個名為 merchantData.json 的檔案並把以下假資料加上去

[
  {
    "id": "1",
    "name": "gogo",
    "adress": "300 新竹市東區關新街xx號",
    "phone": "03 668 7123",
    "website": "https://www.facebook.com/gogofreshtea.tw/",
    "logo": "https://dummyimage.com/280x150/8a8a8a/fff"
  },
  {
    "adress": "300新竹市東區建功一路XX號",
    "id": "2",
    "logo": "https://dummyimage.com/280x150/8a8a8a/fff",
    "name": "天地茶會",
    "phone": "+88635165123",
    "website": "https://ice-cream-and-drink-shop-2406.business.site/"
  },
  {
    "id": "3",
    "adress": "30068新竹市東區學府路XX號",
    "logo": "https://dummyimage.com/280x150/8a8a8a/fff",
    "name": "飲料王",
    "phone": "+88635165123",
    "website": "http://www.chingshin.tw/product.php"
  },
  {
    "adress": "300新竹市東區金山街XXX樓",
    "id": "4",
    "logo": "https://dummyimage.com/280x150/8a8a8a/fff",
    "name": "很渴紅茶",
    "phone": "+88635630123",
    "website": "http://www.kebuke.com/#shop"
  },
  {
    "id": "5",
    "name": "gogo3",
    "adress": "300 新竹市東區關新街xx號",
    "phone": "03 668 7123",
    "website": "https://www.facebook.com/gogofreshtea.tw/",
    "logo": "https://dummyimage.com/280x150/8a8a8a/fff"
  },
  {
    "id": "6",
    "name": "gogo4",
    "adress": "300 新竹市東區關新街xx號",
    "phone": "03 668 7123",
    "website": "https://www.facebook.com/gogofreshtea.tw/",
    "logo": "https://dummyimage.com/280x150/8a8a8a/fff"
  },
  {
    "id": "7",
    "name": "gogo5",
    "adress": "300 新竹市東區關新街xx號",
    "phone": "03 668 7123",
    "website": "https://www.facebook.com/gogofreshtea.tw/",
    "logo": "https://dummyimage.com/280x150/8a8a8a/fff"
  }
]

發出 HTTP 的 GET 呼叫

在 merchants.service.ts 中,注入 HttpClient (第 7 行),然後新增一個方法 fetchMerchant(),此方法目的在於將商家的資料取得後,更新 merchants$ 這個 BehaviorSubject ,有訂閱的就會收到更新的通知。在 fetchMerchant() 使用 HttpClient 的 get 方法,並傳入 api endpoint 作為參數,此方法會把 response 以 observable 的方式回傳(第 10~12 行)。

// ...省略
@Injectable({
  providedIn: 'root',
})
export class MerchantsService {
  merchants$ = new BehaviorSubject<Merchant[]>([]);
  constructor(private clonerService: ClonerService, private http: HttpClient) {}

  fetchMerchant(): void {
    this.http
      .get('./assets/merchantData.json')
      .subscribe((merchants: Merchant[]) => this.merchants$.next(merchants));
  }
 // ...省略

之後在 merchant-list.component.ts 初始化時,呼叫 service 的 fetchMerchant() 方法,載入商家資訊。

// ...省略
@Component({
  selector: 'app-merchant-list',
  templateUrl: './merchant-list.component.html',
  styleUrls: ['./merchant-list.component.scss'],
})
export class MerchantListComponent implements OnInit {
  merchants$: Observable<Merchant[]>;

  constructor(
    private merchantsService: MerchantsService,
    public dialog: MatDialog
  ) {}

  ngOnInit(): void {
    this.merchantsService.fetchMerchant();
    this.merchants$ = this.merchantsService.getMerchants();
  }
 // ...省略

結語

今天的程式碼,由於在寫這篇時還沒完成串接,所以這裡就很簡單的介紹,未來等串結完成後,在把詳細的介紹補上。Angular 的主要概念就先講到這邊!


上一篇
[Day22] Angular 主要概念 - 路由
下一篇
[Day24] GO Bot使用 (含申請與串接)
系列文
從零開始的點餐系統,Google好棒棒30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言