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. JMeter接口测试实战-动态数据验证

    JMeter接口测试实战-动态数据验证 说到验证就不得不说断言, 先来看下JMeter官方给出断言(Assertion)的定义, 用于检查测试中得到的响应数据等是否符合预期,用以保证测试过程中的数据交 ...

  2. 【Objective-C学习笔记】变量和基本的数据类型

    OC是增强了C的特性,所以在变量和基本数据类型上基本与C一致. 在OC中变量命名有如下规则: 由字母.数字.下划线.$符号组成 必须以字母.下划线.$符号开头 大小写敏感 在OC中定义变量的时候不能使 ...

  3. MongoDB中数组类型相关的操作

    概述 在MongoDB的模式中,我们经常将一些数据存储到数组类型中,即我们常见的嵌套模式设计的一种实现方式.数组的这种设计实现方式在关系数据库中是没有或者说不常见的.所以,通过本文我们来梳理一下Mon ...

  4. git开发常用命令

    1.基本命令git branch 查看本地分支git branch -r 查看远程分支git checkout xxx 切换分支git pull origin master //从远程同步到本地,ma ...

  5. 数据库微信特殊表情编码django设置

    #settings.py DATABASES = { 'default': { 'OPTIONS': { "init_command":"SET foreign_key_ ...

  6. mysql的使用相关问题

    MySQL的使用和密码忘记解决 解决步骤: 1.查看:我的电脑--管理--服务--查看mysql路径---一直到mysql下的bin文件夹     或需转回别的磁盘: G: (C:\Users\Adm ...

  7. Win 10 无法打开内核设备“\\.\Global\vmx86”问题

    Win 10操作系统, VMWareWorkstation10 无法打开内核设备"\\.\Global\vmx86": 系统找不到指定的文件.你想要在安装 VMware Works ...

  8. jquery各大学选择插件

    地址:http://www.jq22.com/jquery-info5565 演示地址:http://www.jq22.com/yanshi5565

  9. 【题解】UVA11362 Phone List

    Tags : ​ 排序,字典树 ​ 从短到长排序,逐个插入字典树.若与已有的重复,返回错误信息. #include <iostream> #include <stdio.h> ...

  10. 一个简单的以太坊合约让imtoken支持多签

    熟悉比特币和以太坊的人应该都知道,在比特币中有2种类型的地址,1开头的是P2PKH,就是个人地址,3开头的是P2SH,一般是一个多签地址.所以在原生上比特币就支持多签.多签的一个优势就是可以多方对一笔 ...