老是遇到很多坑等着自己去填.
首先创建服务器:
1.最好使用express,这个库有更多的api,方法:npm install express --save;
2. npm install @types/express --save;
安装nodemon 可以让服务器自动重启,
方法:npm install nodemon;
在启动服务器的时候用:nodemon build/...js;
这样服务器就算启动完成了.
/** * Created by Administrator on 2017/5/16. */ import * as express from "express"; const app=express(); app.get("/",(req,res)=>{ res.send("hello express") }) export class Produce{ constructor( public id:number,public title:string,public price:number,public rating:number,public desc:string,public categories:Array<any> ){ } } const products:Produce[] =[ new Produce(1,"第一个商品",1.99,3.5,"这是第一个商品描述",["图书","音乐"]),new Produce(2,"第二个商品",3.99,2.5,"这是第二个商品描述",["语文"]),new Produce(3,"第三个商品",4.99,4.5,"这是第三个商品描述",["音乐","体育"]),new Produce(4,"第四个商品",5.99,1.5,"这是第四个商品描述",["化学",new Produce(5,"第五个商品",16.99,"这是第五个商品描述",["生物","图书"]),new Produce(6,"第六个商品",12.99,"这是第六个商品描述",["科学"]),] app.get("/api/products",res)=>{ res.json(products) }) app.get("/api/products/:id",res)=>{ //在命令行中打印,当发送个请求的时候才触发,// console.log(req.params) res.json(products.find( produce => produce.id==req.params.id)) }) const server =app.listen(8000,"localhost",()=>{ console.log("服务器已经启动,地址是http://localhost:8000") });
接着在本地从创建好的服务器上获取数据:
import { Component,OnInit } from '@angular/core'; import {Observable} from "rxjs"; 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) { console.log(http) this.dataSource = this.http.get('/api/products') .map((res)=>res.json()) console.log(this.dataSource) } ngOnInit() { this.dataSource.subscribe((data)=>{ this.products=data }) } }
dataSource:Observable<any> 将获得的数据保存为流.对应 的需要引入Observable from "rxjs"
http服务已经在app.module中引入过了,这里需要声明在构造函数里头,并引入Http from "@angular/Http";
接着就是坑了,写完后,发现还是获取不到服务器上的数据:
接下来还有配置:
在根目录新建一个文件:proxy.conf.json 内容为:
{ "/api":{ "target":"http://localhost:8000" } }
"start": "ng serve --proxy-config proxy.confi.json",
然后启动
要用npm run start;
只要使用这个命令,才能告诉页面,需要到这个地址去拿数据.