您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息
三六零分类信息网 > 遂宁分类信息网,免费分类信息发布

怎样操作Angular实现数据请求

2025/2/11 9:51:06发布7次查看
这次给大家带来怎样操作angular实现数据请求,操作angular实现数据请求的注意事项有哪些,下面就是实战案例,一起来看一下。
使用 angular 请求数据的时候,需要引入 httpmodule 模块,如果使用的 jsonp 模式的话,则需要另外引入 jsonpmodule 模块
import { httpmodule, jsonpmodule } from '@angular/http'
然后在当前模块中的 imports 内进行注册
imports: [  httpmodule,  jsonpmodule ],
注册以后就可以在组件文件当中引入相对应的方法来进行数据请求了
import { http, jsonp } from '@angular/http'
然后在当前组件的构造函数当中进行注入以后就可以使用了
constructor(private http: http, private jsonp: jsonp) { }
使用如下,一个简单的 get 请求
// 进行注入,拿到相对应的方法 constructor(private http: http, private jsonp: jsonp) { } public list: any = [] // 请求数据 getdata() {  let url = 'http://www.phonegap100.com/appapi.php?a=getportallist&catid=20&page=1'  let _this = this  this.http.get(url).subscribe((data) => {   _this.list = json.parse(data['_body'])['result']   console.log(_this.list)  }) }
前台进行渲染即可
<button (click)="getdata()">get 请求数据</button> <ul>  <li *ngfor="let item of list">   {{item.title}}  </li> </ul>
jsonp 请求数据
注意区分与 get 请求的区别,使用如下
// 请求数据 jsonpdata() {  let url = 'http://www.phonegap100.com/appapi.php?a=getportallist&catid=20&page=1&callback=jsonp_callback'  let _this = this  this.jsonp.get(url).subscribe((data) => {   _this.list = data['_body']['result']   console.log(_this.list)  }) }
// 渲染 <button (click)="jsonpdata()">jsonp 请求数据</button> <ul>  <li *ngfor="let item of list">   {{item.title}}  </li> </ul>
不同点
请求的 url 参数结尾必须要添加指定的回调函数名称 &callback=jsonp_callback
请求的方式变为 this.jsonp.get(url)
请求后得到的数据格式不统一,需要自行进行调整
post 请求
与 get 的请求方式有些许不同,首先需要引入请求头 { headers }
import { http, jsonp, headers } from '@angular/http'
然后来对请求头进行定义,需要先实例化 headers
private headers = new headers({'content-type': 'application/json'})
最后在提交数据的时候带上 headers 即可
postdata() {  let url = 'http://localhost:8080/login'  let data = {   username: zhangsan,   password: 123  }  this.http.post(   url,   data,   {headers: this.headers}  ).subscribe((data) => {   console.log(data)  }) }
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
怎样操作node使用promise替代回调函数
如何使用vue + better-scroll实现移动端字母索引导航
以上就是怎样操作angular实现数据请求的详细内容。
遂宁分类信息网,免费分类信息发布

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录