在使用angular2中使用nodejs创建服务器,并成功获取参数
為什么80%的碼農(nóng)都做不了架構(gòu)師?>>> ??
老是遇到很多坑等著自己去填.
首先創(chuàng)建服務(wù)器:
1.最好使用express,這個庫有更多的api,方法:npm install express --save;
2. npm install @types/express --save;
安裝nodemon 可以讓服務(wù)器自動重啟,
方法:npm install nodemon;
在啟動服務(wù)器的時候用:nodemon build/...js;
這樣服務(wù)器就算啟動完成了.
/*** 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,"這是第四個商品描述",["化學(xué)","體育"]),new Produce(5,"第五個商品",16.99,4.5,"這是第五個商品描述",["生物","圖書"]),new Produce(6,"第六個商品",12.99,3.5,"這是第六個商品描述",["科學(xué)"]), ]app.get("/api/products",(req,res)=>{res.json(products) }) app.get("/api/products/:id",(req,res)=>{//在命令行中打印,當(dāng)發(fā)送個請求的時候才觸發(fā),// console.log(req.params)res.json(products.find( produce => produce.id==req.params.id)) })const server =app.listen(8000,"localhost",()=>{console.log("服務(wù)器已經(jīng)啟動,地址是http://localhost:8000") });接著在本地從創(chuàng)建好的服務(wù)器上獲取數(shù)據(jù):
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> 將獲得的數(shù)據(jù)保存為流.對應(yīng) 的需要引入Observable from "rxjs"
http服務(wù)已經(jīng)在app.module中引入過了,這里需要聲明在構(gòu)造函數(shù)里頭,并引入Http from "@angular/Http";
?
接著就是坑了,寫完后,發(fā)現(xiàn)還是獲取不到服務(wù)器上的數(shù)據(jù):
接下來還有配置:
在根目錄新建一個文件:proxy.conf.json ?內(nèi)容為:
{"/api":{"target":"http://localhost:8000"} }?
然后在package.json文件中,修改一行
"start": "ng serve --proxy-config proxy.confi.json",然后啟動
要用npm run start;
只要使用這個命令,才能告訴頁面,需要到這個地址去拿數(shù)據(jù).
?
轉(zhuǎn)載于:https://my.oschina.net/kaykie/blog/902253
總結(jié)
以上是生活随笔為你收集整理的在使用angular2中使用nodejs创建服务器,并成功获取参数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: lvs初步认识
- 下一篇: 干货 | OneAPM研发总监高海强:百