與json-server對接,爲組件提供CRUD API功能

# 工程所要實現的功能:

與json—server對接,爲組件提供CRUD API

#實現思路

注意:前提條件,必定要啓動json-server(啓動方法:進入db.json所在文件路徑 ,終端輸入:json-server --watch db.json )

驗證json-server 是否可用。方法:http://localhost:3000/products 有返回數據

1. 引入HttpClientModule

 


2. 建立一個類(Product)
ng g class product

 


export class Product {
id: 1;
title: number;
detail: number;
price:number;
}

3. 建立一個service(Product.service.ts)
ng g service product --spec=false

 


注意事項:
1.標註返回的數據類型<Product[]>、<Product>
2.建立了5個API:
Get
GetById
Post
Put
Delete

4. 建立component(home), 獲取後臺數據
導入所建立的service(Product service)
導入Product類
調用service,經過調用Observable的subscribe 方法。

 


調用subscribe 返回的數據類型是Product[],這個數據類型取決於service返回的數據類型
getProducts(){
return this.http.get<Product[]>(this.baseUrl);

}



5. 編寫component.html,展現商品

注意事項:*ngFor所在的位置相當重要,*ngFor做用:把*ngFor所在的div(標籤element)做循環

好比:<tr *ngFor="let product of products">
它是把tr做了循環,循環多少次呢?取決於products數組的長度

 


6. 一般的規範
在template中,=等號的右邊:須要雙引號""

class="btn"
(click)="onClick()"
[hidden]="true"

只要是方法,無論是class,仍是在template中,都要帶()
如:onClick();

在template中,在class中,對字符串不區分雙引號仍是單引號

#小結
1. 優化了登陸表單驗證的用戶體驗
2. 掌握了json-server的建立
3. 熟悉了HTTP的CRUD請求方式
4. 建立了一個service,與json-server對接,並提供了CRUD APi
5. 建立template,展現全部的商品,並構建了入口按鈕
相關文章
相關標籤/搜索