一、在项目的根目录下创建一个proxy.conf.json文件,文件所在位置如图 这里写图片描述

文件代码

{
    "**": {
        "target": "http://localhost:8000", // 指向需要代理的api地址
        "secure":false
    }
}

二、修改package.json文件

ng serve --proxy-config proxy.conf.json
1
这里写图片描述

三、利用nodejs的express框架创建一个后端服务

> const express = require("express");
> 
> const app = express();
> 
> let dataSet = [
>     {"id":"0","name":"张三","age":20},
>     {"id":"1","name":"李四","age":34},
>     {"id":"2","name":"王五","age":30},
>     {"id":"3","name":"马六","age":50} ]; app.get("/products",(req,res)=>{
>     res.json(dataSet); });
> 
> app.listen(8000,"localhost",()=>console.log("服务已经启动"))

四、案例demo代码

//ts文件
import {Component, OnInit} from '@angular/core';
import {Observable} from "rxjs/Observable";
import {Http} from "@angular/http";
import "rxjs/Rx";

@Component({
  selector: 'app-httpdemo',
  templateUrl: './httpdemo.component.html',
  styleUrls: ['./httpdemo.component.css']
})
export class HttpdemoComponent implements OnInit {
  dataSource: Observable<any>;
  dataSet: Array<any> = [];

  constructor(private http: Http) {
    this.dataSource = this.http.get("/products").map((res) => res.json());
  }

  ngOnInit() {
    this.dataSource.subscribe(
      (data) => this.dataSet = data
    )
  }

}
//html代码
<ul>
  <li *ngFor="let item of dataSet">{{item.name}}--{{item.age}}</li>
</ul>

五、运行效果 这里写图片描述

六、重要说明:启动服务的时候必须用npm run start启动,代理才生效,如果用ng serve启动代理不生效


Sting
4 声望0 粉丝