zoukankan      html  css  js  c++  java
  • angular2

    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:[]
  • 相关阅读:
    Node.js 笔记03
    Node.js 笔记02
    Node.js 笔记01
    源代码管理工具-git
    ES6笔记01
    07_查找、软链接、打包压缩、软件安装
    06_系统信息相关命令
    oracle序列中cache和nocache
    PL/SQL规范、块、过程、函数、包、触发器
    对Xcode菜单选项的详细探索(干货)
  • 原文地址:https://www.cnblogs.com/zhangjinting/p/6666670.html
Copyright © 2011-2022 走看看