Angular4.x请求

码云地址:

https://gitee.com/ccsoftlucifer/Angular4Study

1. 搭建工程

新建一个工程angulardemo03

ng new angulardemo03

npm install 更新依赖

2. 新建组件

在app目录新建文件夹components,自己自定义的所有的组件都放在这个目录下面.

ng g component components/news

目录结构如下:

3.添加请求相关的model

编辑app.modle.ts

 import { HttpClientModule  } from '@angular/common/http'; 
 @NgModule({
declarations: [
AppComponent,
NewsComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})

4.编写代码

news.component.html 编写一个按钮用来发送请求:

<h2>你好angular</h2>
<p>
news works!
</p> <br>
<button (click)="requestData()">请求数据</button>
从服务器拿到的值:
{{value}}

news.component.ts编写逻辑,导入http服务

 import { Component, OnInit } from '@angular/core';

 import {HttpClient} from '@angular/common/http';
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit {
public value:any
constructor(private http:HttpClient) { } ngOnInit() {
// this.http.get('http://localhost:8080/user/findUser?id=1')
// .subscribe(res=>{ this.value = res }) }
//请求数据方法
requestData(){
console.log('请求数据');
var url='http://localhost:8080/user/findUser?id=1';//这里定义一个地址,要允许跨域
this.http.get(url).subscribe(function(data){
console.log(data);
},function(err){
console.log(err);
})
} }

5.解决跨域

  由于前端工程是localhost:4200,请求后端工程Localhost:8080,会出现跨域错误:

  Access-Control-Allow-Origin' header is present on the requested resource.

  解决办法:

  5.1 在项目的根目录添加proxy.config.json文件

  

 {
"/": {
"target": "http://localhost:8080/"
}
}

  5.2修改package.json文件

 "scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.config.json",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},

  5.3修改angular.json

 "serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "angulardemo03:build",
"proxyConfig":"proxy.config.json"
},
"configurations": {
"production": {
"browserTarget": "angulardemo03:build:production"
}
}
},

  5.4服务器端添加注解

  @CrossOrigin(origins = "http://localhost:4200",allowCredentials = "true")

  

这样数据就拿过来了啦~

  使用RxJS进行请求发送:

 import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent,  SubscriptionLike, PartialObserver, concat } from 'rxjs';
import { map, filter, scan } from 'rxjs/operators';
import { webSocket } from 'rxjs/webSocket';
import { ajax } from 'rxjs/ajax';
import { TestScheduler } from 'rxjs/testing';

  请求:

 //另外一种请求方式
useRxJsRequestData(){
var _result=this;
console.log('请求数据');
if(this.inputValue==''){
//用户没有输入
alert('请先输入值');
}else{
//用户有输入的值
var url='http://localhost:8080/user/findUser?id='+this.inputValue;
this.http.get(url).subscribe(res =>{
console.log(res);
console.log(typeof(res));
console.log(res['id']);
var _this = this; _this.obj.id=res['id'];
_this.obj.useName=res['userName'];
_this.obj.password=res['password'];
_this.obj.age=res['age'];
})
//console.log(map);
}
}

Angular4.x跨域请求的更多相关文章

  1. Laravel中的ajax跨域请求

    最近接触Laravel框架ajax跨域请求的过程中遇到一些问题,在这里做下总结. 一开始发起ajax请求一直报500错误,搜索相关资料后发现Laravel要允许跨域请求可以加入Cors中间件,代码如下 ...

  2. 跨域请求——WebClient通过get和post请求api

    AJAX不可以实现跨域请求,经过特殊处理才行.一般后台可以通过WebClient实现跨域请求~ //get 请求        string url = string.Format("htt ...

  3. 原生js封装ajax,实现跨域请求

    描述: 需要ajax跨域请求,用cors跨域方案.服务端设置: header('Access-Control-Allow-Origin: http://front.ls-la.me'); header ...

  4. 关于试用jquery的jsonp实现ajax跨域请求数据的问题

    我们在开发过程中遇到要获取另一个系统数据时,就造成跨域问题,这就是下文要说的解决办法: 先我们熟悉下json和jsonp的区别: 使用AJAX就会不可避免的面临两个问题,第一个是AJAX以何种格式来交 ...

  5. 【JavaScript】--重点解析之跨域请求

    JSON JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式. JSON是用字符串来表示Javascript对象,例如可以在django中发送一个JSON格式 ...

  6. 利用CORS实现跨域请求(转载)

    跨域请求一直是网页编程中的一个难题,在过去,绝大多数人都倾向于使用JSONP来解决这一问题.不过现在,我们可以考虑一下W3C中一项新的特性--CORS(Cross-Origin Resource Sh ...

  7. Ajax_05之跨域请求

    1.跨域请求: Cross Domain Request:跨域名的HTTP请求,浏览器从某个域名下的资源访问了另一域名下的另一资源(协议.域名或是端口号不同): ①浏览器允许跨域请求的情形:  < ...

  8. 浅谈linux 下,利用Nginx服务器代理实现ajax跨域请求。

    ajax跨域请求对于前端开发者几乎在任何一个项目中都会用到,众所周知,跨域请求有三种方式: jsonp; XHR2 代理: jsonp: 这种应该是开发中是使用的最多的,最常见的跨域请求方法,其实aj ...

  9. 解决ajax跨域请求 (总结)

    ajax跨域请求,目前已用几种方法实现:   1)用原生js的xhr对象实现.                var url="http://freegeoip.net/json/" ...

随机推荐

  1. 教你一步永久激活WebStorm2018

    工欲善其事必先利其器,我们在开发过程中,编辑器是我们提高开发效率及生产必备的工具,如何发现一个高效好用的编辑器是程序员必备的技能之一. 前端开发有众多编辑器 sublime.vscode.webstr ...

  2. java或Jmeter实现两个日期相加减(2003-06-01-2003-05-01)

    在beanshell中写入如下代码, import java.io.FileInputStream; SimpleDateFormat myFormatter = new SimpleDateForm ...

  3. php连接数据库,以及日期处理函数

    php连接数据库,以及日期处理函数 $conn=mysql_connect("10.0.10.0:0000","root","123456" ...

  4. 一键安装Cloud Torrent

    wget -N --no-check-certificate https://raw.githubusercontent.com/ToyoDAdoubi/doubi/master/cloudt.sh ...

  5. Java 8 Stream介绍及使用2

    (原) stream中另一些比较常用的方法. 1. public static<T> Stream<T> generate(Supplier<T> s) 通过gen ...

  6. 015_python原生在线调试工具

    一.pdb https://docs.python.org/3/library/pdb.html

  7. JProfiler的详细使用介绍

    转:https://blog.csdn.net/huangjin0507/article/details/52452946 下载软件 官网地址:http://www.ej-technologies.c ...

  8. Vue.Draggable 文档总结

    本文章转自https://blog.csdn.net/zjiang1994/article/details/79809687 Vue.Draggable学习总结 Draggable为基于Sortabl ...

  9. windows环境中JDK环境变量配置

    一.环境准备 Windows10 jdk-9.0.1 二.下载并安装JDK 到Java的官网下载JDK安装包,地址:http://www.oracle.com/technetwork/java/jav ...

  10. QinQ 简介

    QinQ 是一种二层隧道协议,通过将用户的私网报文封装上外层 VLAN Tag,使其携带两层 VLAN Tag 穿越公网,从而为用户提供了一种比较简单的二层VPN隧道技术.QinQ 的实现方式可分为两 ...