方法一:get请求数据
1、 HttpClientModule导入
app.module.ts
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
HttpClientModule,
],
declarations: [ ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
2、注入到服务中
目的:获取数据并与外部 API 和资源进行交互。
cart.service.ts
import { HttpClient } from '@angular/common/http';
export class CartService {
constructor(private http: HttpClient) {}
getShippingPrices() {
return this.http.get('/assets/shipping.json');
}
}
3、从 shipping.json 文件中通过 HTTP 检索配送数据
1)shipping.component.ts
import { CartService } from '../cart.service'; //1、 导入
export class ShippingComponent implements OnInit {
shippingCosts; //2、定义
constructor(private cartService: CartService) { } //3、注入
ngOnInit(): void {
this.shippingCosts = this.cartService.getShippingPrices(); //设置属性
}
2)cart.service.ts
getShippingPrices(){
return this.http.get('./assets/shipping.json');
}
3)cart.component.html
<a routerLink="/shipping">Shipping Prices</a>
4)shipping.component.html
<div class="shipping-item" *ngFor="let shipping of shippingCosts | async">
<span>{{ shipping.type }}</span>
<span>{{shipping.price | currency }}</span>
</div>
async 管道从数据流中返回最新值,并在所属组件的生命期内持续返回
方法二:post向服务器提交数据(可能存在跨域问题)
0、运行app.js
- npm install 安装依赖
- cd到app.js文件夹下使用终端/powershell 输入:node app.js
1、app.module.ts中引入HttpClientModule
import { HttpClientModule } from '@angular/common/http';
2、在使用post方法的组件中引入HttpHeaders
import { HttpHeaders } from '@angular/common/http';
3、写dom
<button (click)="postData()">post向服务器提交数据</button>
4、写提交方法
postData(){
//固定用法
const httpOptions = {headers: new HttpHeaders({ 'Content-type': 'application/json' })};
//存在跨域
var api = 'http://127.0.0.1:3000/dologin';
this.http.post(api,{"username":"张三",'age':20},httpOptions).subscribe((response) => {
console.log(response);
})
}
在服务器接收到传入数据
方法三:jsonp获取数据(允许跨域)
1、查看服务器是否支持jsonp
2、在app.module.ts中引入HttpClientJsonpModule(记得声明)
import {HttpClientJsonpModule } from '@angular/common/http';
3、写dom
<button (click)="jsonpGetData()">jsonp获取数据</button>
4、写方法
jsonpGetData(){
var api = 'http://a.itying.com/api/productlist';
this.http.jsonp(api,'callback').subscribe((response) =>{
console.log(response);
})
}