博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
angular2
阅读量:4565 次
发布时间:2019-06-08

本文共 1149 字,大约阅读时间需要 3 分钟。

1、定义服务

import {Injectable} from "@angular/core";import {Http, Jsonp} from "@angular/http";import "rxjs/add/operator/map";@Injectable()export class HttpServer {  constructor(public jsonp: Jsonp, public http: Http) {  } /*  *   url: 服务器api接口地址  *   params: 传递参数对象  */  // get方法  httpGet(url, params) {    return this.http.get(url, {search: params}).map(res=>res.json);  }  // post方法  httpPost(url, params) {    return this.http.post(url, {search: params}).map(res=>res.json);  }  // 跨域请求  jsonpGet(url, params) {    return this.jsonp.get(url, {search: params}).map(res=>res.json());  }}

2、app.module.ts文件中引入服务

import {HttpServer} from "./http.server.ts";...providers: [HttpServer]...

3、组件中使用服务获取数据

...import {URLSearchParams} from "@angular/http";...// 使用服务// 设置参数var params = new URLSearchParams();params.set("callback", "JSONP_CALLBACK");// 调用jsonpGet方法,跨域请求数据httpServer.jsonpGet("http://localhost:3000/users", params).subscribe(res=> {  console.log(res);});
1. 服务需要在constructor(public httpServer: HttpServer)参数中初始化, this.httpServer.httpGet()2. 服务有两种引入方式,如果在全局引入,那么组件中还要引入文件路径,不用写,providers:[]

转载于:https://www.cnblogs.com/zhangjinting/p/6666670.html

你可能感兴趣的文章
一个python的计算熵(entropy)的函数
查看>>
spring源码学习——spring整体架构和设计理念
查看>>
模拟window系统的“回收站”
查看>>
OpenCV中的split函数
查看>>
MongoDB divide 使用之mongotempalte divide
查看>>
SSH不允许进行DNS解析
查看>>
Git(介绍和安装)
查看>>
磁盘管理
查看>>
重写与重载
查看>>
Python 爬取qqmusic音乐url并批量下载
查看>>
Java代码获取spring 容器的bean几种方式
查看>>
2015年3月5日(元宵节)——substr()与substring()的区别
查看>>
mysql 导出查询结果到文件
查看>>
Js参数值中含有单引号或双引号解决办法
查看>>
python5
查看>>
js转换/Date(........)/
查看>>
mysql中limit用法
查看>>
C#开源爬虫NCrawler源代码解读以及将其移植到python3.2(1)
查看>>
c++ std::thread + lambda 实现计时器
查看>>
NSRunLoop个人理解
查看>>