angular4.0 HTTP初级,nodejs搭建服务器,并使用

看了一点与服务器通讯的知识,整理一下今天get到的一点关于http的知识,非常简单 可能都够不成初级(手动笑哭)
首先说一下如何搭建一个服务器,
1.创建一个空的工程,
2.npm init -y, ide自动生成一个package.json文件,如下图
这里写图片描述
3.npm i @types/node --save,ide生成node_modules文件夹和package-lock.json文件,作用:引入node的类型定义文件 可以在typesscript里用javascript的库
4.创建一个新的tsconfig.json文件 他是用来告诉编译器如何将typesscript编译成javascript

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "outDir": "build",
    "lib": ["es6"]
  },
  "exclude": [
    "node_modules"
  ]
}

5.在file的setting菜单里进行相关设置,最终是下图这样子
这里写图片描述
6.配置好了,就开始写一个简单的程序,创建一个server文件夹,hello_server.ts(会自动生成一个build文件夹js文件也会自动生成,只修改ts文件就可以了)
6.运行 node build/hello_sever.js
下面贴一下服务器的数据
这里写图片描述

hello_sever.ts

import * as http from  'http'
const server = http.createServer((request,response) => {
    response.end("hello Node");
});
server.listen(8000);

package.json

{
  "name": "untitled",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/express": "^4.0.36",
    "@types/node": "^8.0.20",
    "express": "^4.15.4"
  }
}

tsconfig.ts

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "outDir": "build",
    "lib": ["es6"]
  },
  "exclude": [
    "node_modules"
  ]
}

需要注意的是node不会自动加载服务器变化的文件的,只能够重新启动node服务器(node build….),可以安装一个工具,自动重启node服务器,只需要刷新浏览器即可更新文件内容,npm install -g nodemon,然后用nodemon build/hello_sever.js

下一步,在自己的应用中使用自己创建的服务器里的数据

先描述一下要实现的功能,我要用auxtion_server.ts里的product数据,传入products,然后展示在product组件上,根据服务器里的数据,创建li标签

1.首先app.module.ts里要引入http模块

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { ProductComponent } from './product/product.component';
import {HttpModule} from '@angular/http';
import {FormsModule} from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent,
    ProductComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

2.创建一个proxy.conf.json的文件,按如下配置

{
  "/api": {
    "target": "http://localhost:8000"
  }
}

3.配置完以后要在package.json文件的start里添一段代码

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

4.product.component.ts

import { Component, OnInit } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Http, Headers} 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: Observable<any>;
  // private url = 'api/products';
// products: Array<any> = [];
  constructor(private http: Http) {
    //this.dataSource = this.http.get('api/products')
    let myHeaders: Headers = new Headers();
    myHeaders.append('Authorization', 'Basic 123456');

    this.products = this.http.get('api/products', {headers: myHeaders})
      .map((res) => res.json());
  }

  ngOnInit() {
    // this.dataSource.subscribe(
    //   (data) => this.products = data
    // );
    // console.log('222222frfr2222' + this.products);
  }

}

product.compoent.html

<div>
  商品信息ssssss
</div>
<ul>
  <li *ngFor="let product of products | async">
    {{product.title}}
  </li>
</ul>
<!--{{products}}/-->

comments部分是第二种方法,这种比较繁琐,

import { Component, OnInit } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Http, Headers} 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>;
  // private url = 'api/products';
products: Array<any> = [];
  constructor(private http: Http) {
    let myHeaders: Headers = new Headers();
    myHeaders.append('Authorization', 'Basic 123456');
    this.dataSource = this.http.get('api/products', {headers: myHeaders}).map((res) => res.json());
  }

  ngOnInit() {
    this.dataSource.subscribe(
      (data) => this.products = data,
    );
    console.log('222222frfr2222' + this.products);
  }
}

product.component.html,只有li便签无需async那个管道,其他代码一样就不贴了

<li *ngFor="let product of products">
    {{product.title}}
  </li>

效果图都是一样的,那个头部也可以不传,
这里写图片描述

官方文档的http部分有很多。。。看了之后再补充吧

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值