angualrs4 http请求
配置后端服务器地址
node搭建简单的web服务器:http://www.cnblogs.com/Caiyilong/p/8676693.html
在根目录创建proxy.conf.json文件,配置服务器接口,后台访问地址:http://localhost:8000/api/products
{ "/api":{ "target":"http://localhost:8000" } }
修改package.json中的启动命令:启动时使用命令$ npm run start
"start": "ng serve", //改为 "start": "ng serve --proxy-config proxy.conf.json",
前端代码
product.component.html
<div> 商品信息 </div> <ul> <li *ngFor="let product of products"> {{product.title}} </li> </ul>
product.component.ts
import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Http } from '@angular/http'; import 'rxjs/Rx'; @Component({ selector: 'app-product', templateUrl: './product.component.html', styleUrls: ['./product.component.css'] }) export class ProductComponent implements OnInit { //定义一个流 dataSource:Observable<any>; products:Array<any> = []; constructor(private http:Http) { //get请求,返回json类型的流 this.dataSource = this.http.get("/api/products") .map((res) => res.json()); } ngOnInit() { this.dataSource.subscribe( (data) => this.products = data ) } }
使用async管道:
product.component.html
<div> 商品信息 </div> <ul> <li *ngFor="let product of products | async"> {{product.title}} </li> </ul>
product.component.ts
import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Http } from '@angular/http'; import 'rxjs/Rx'; @Component({ selector: 'app-product', templateUrl: './product.component.html', styleUrls: ['./product.component.css'] }) export class ProductComponent implements OnInit { //使用async管道 products:Observable<any>; constructor(private http:Http) { //get请求,返回json类型的流 this.products = this.http.get("/api/products") .map((res) => res.json()); } ngOnInit() {} }