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:[]
  • 相关阅读:
    关于PowerShell调用Linq的一组实验
    PowerShell创建参考窗口
    Python切图脚本
    11->8
    用Python演奏音乐
    关于Haskell计算斐波那契数列的思考
    傅立叶变换与小波分析
    堆排序(python实现)
    二进制数据表示方式
    oracle数据插入/查询乱码
  • 原文地址:https://www.cnblogs.com/zhangjinting/p/6666670.html
Copyright © 2011-2022 走看看