AngularJS 与 server 通信

来源:互联网 发布:关晓彤用的直播软件 编辑:程序博客网 时间:2024/04/29 21:45

一、搭建AngularJS 框架

详细过程请参考官网教程:https://angular.io/guide/quickstart


在上面的截图中出现了两个错误提示:

1. ng server --open 是启动angular 需要在项目目录下执行,而我是在IdeaProjects根目录下执行的,所以报错

2. 第二个错误是因为我启动了其他angular项目,导致端口被占用,关掉其他项目就释放了4200端口,当然也可以在程序中修改端口号


启动成功以后,浏览器会弹出相应的欢迎页面


二、与server 端进行通信

1. 在src-->app-->app.component.html 文件中接受server端返回的数据

<!--The content below is only a placeholder and can be replaced.--><div style="text-align:center">  <h1>    Welcome to {{title}}!  </h1></div><h2>  From tomcat {{data._body}}</h2>
2. 在src-->app-->app.component.ts 文件中配置HTTP请求

import {Component, OnInit} from '@angular/core';import {Http} from '@angular/http';@Component({  selector: 'app-root',  templateUrl: './app.component.html',  styleUrls: ['./app.component.css']})export class AppComponent implements OnInit {  data: any;  title = 'app';  constructor(private _http: Http) {  }  ngOnInit(): void {    this.data = this._http.get('de/control/test')      .subscribe(data => {        this.data = data;        console.log(this.data._body);      });  }}

现在打开浏览器,会发现有错误


3. 在app.moudule.ts中引入HTTP模块

import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { AppComponent } from './app.component';import {HttpModule} from '@angular/http';@NgModule({  declarations: [    AppComponent  ],  imports: [    HttpModule, // 引入HTTP模块    BrowserModule  ],  providers: [],  bootstrap: [AppComponent]})export class AppModule { }
打开浏览器发现get请求中的端口不对

4. 我们在当前项目目录下新建proxy.conf.json

{"/de" : {"target" : "http://localhost:8081","secure" : false}}
在终端运行 ng serve --proxy-config proxy.conf.json 所有以de开头的URL请求都会发送到target



5.启动server端的服务


6.打开浏览器,服务端成功返回结果Hello CUEB!


原创粉丝点击