前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >在使用angular2中使用nodejs创建服务器,并成功获取参数

在使用angular2中使用nodejs创建服务器,并成功获取参数

作者头像
杭州前端工程师
发布2018-06-15 12:19:55
4.3K0
发布2018-06-15 12:19:55
举报

老是遇到很多坑等着自己去填.

首先创建服务器:

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,4.5,"这是第五个商品描述",["生物","图书"]),
  new Produce(6,"第六个商品",12.99,3.5,"这是第六个商品描述",["科学"]),
]



app.get("/api/products",(req,res)=>{
  res.json(products)
})
app.get("/api/products/:id",(req,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"
  }
}

然后在package.json文件中,修改一行

"start": "ng serve --proxy-config proxy.confi.json",

然后启动

要用npm run start;

只要使用这个命令,才能告诉页面,需要到这个地址去拿数据.

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档