大佬教程收集整理的这篇文章主要介绍了angular2 Injectable http ng2使用服务(Injectable)加载(http)数据,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
1、 定义服务
import {InjectablE} from "@angular/core"; import {http,Jsonp} from "@angular/http"; import "rxjs/add/operator/map"; @Injectable() export class AppServer { constructor(public http:http,public jsonp:Jsonp) { } // http.get httpGet(url,params) { return this.http.get(url,{search: params}).map(result=>result.json()); } // http.post httpPost(url,params) { return this.http.post(url,params).map(result=>result.json()); } // jsonp jsonpGet(url,params) { return this.jsonp.get(url,{search: params}).map(result=>result.json()); } }
2、 定义组件, 加载服务
import {Component,OnInit} from "@angular/core"; // 获取路由传递传递过来的params(id) 增加模块激活的路由(ActivatedRoutE) import {ActivatedRoutE} from "@angular/router"; import {AppServer} from "./app.service"; import {URLSearchParams} from "@angular/http"; @Component({ SELEctor: "my-info",templateUrl: "../templates/about-info.html",providers: [AppServer] }) export class Ab@R_801_9981@nfoComponent implements OnInit { // 定义一个变量,获取服务方法取得的数据 info:number; data:Array<Object>; // 初始化变量,这里必须加修饰词 public private,初始化服务,然后使用服务方法,调取数据 constructor(public infos:AppServer) { } // 方法中操作id,通过id查询信息等等 ngOnInit(){ var url = "http://localhost:3000/login"; var params = new URLSearchParams(); params.set("id","1"); // 传递过来的不是promise 所以要subscribe执行 this.infos.gethttp(url,params).subscribe(res=> { console.log(res); } ); } }
3、 上面组件中局部加载了这个服务, 如果需要全局导入服务 app.module.ts文件中
providers: [AppServer]配置
以上是大佬教程为你收集整理的angular2 Injectable http ng2使用服务(Injectable)加载(http)数据全部内容,希望文章能够帮你解决angular2 Injectable http ng2使用服务(Injectable)加载(http)数据所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。