相关推荐:《angular教程》
首先模块引入import { browsermodule } from '@angular/platform-browser';import { ngmodule } from '@angular/core';import {formsmodule} from '@angular/forms';import { approutingmodule } from './app-routing.module';import { appcomponent } from './app.component';import {httpclientmodule,httpclientjsonpmodule} from '@angular/common/http'@ngmodule({ declarations: [ appcomponent ], imports: [ browsermodule, approutingmodule, formsmodule, httpclientmodule, httpclientjsonpmodule ], providers: [], bootstrap: [appcomponent]})export class appmodule { }
组件中使用import { component, oninit } from '@angular/core';import { httpclient, httpheaders, httpparams } from '@angular/common/http';import qs from 'qs';@component({ selector: 'app-http', templateurl: './http.component.html', styleurls: ['./http.component.less']})export class httpcomponent implements oninit { constructor(public http: httpclient) { } ngoninit(): void { this.getpostdata(); //post this.gettestdata(); //get this.getjsonpdata() //jsonp } getpostdata() { this.http.post('http://localhost:3000/api/info', { name: 'laney' }, { headers: new httpheaders({ 'content-type': 'application/json' }) }).subscribe((res) => { console.log(res); }) } gettestdata() { var obj1 = { name: 'alice', age: '20' } var params = qs.stringify(obj1); console.log(params) //第一种方式:字符串拼接 this.http.get('http://localhost:3000/api/school?' + params).subscribe((res) => { console.log(res); }) //第二种方式:httpparams var oarma = new httpparams({ fromstring: params }); this.http.get('http://localhost:3000/api/school?', { params: oarma }).subscribe((res) => { console.log(res); }) } getjsonpdata() { this.http.jsonp('http://localhost:3000/getscript', 'callback').subscribe((res) => { console.log(res); }) }
http封装import { injectable } from '@angular/core';import {httpclient,httpheaders,httpparams} from '@angular/common/http';import qs from 'qs';import { environment } from '../../environments/environment';console.log(environment.baseurl);@injectable({ providedin: 'root'})export class rxjsservice { constructor(public http:httpclient) { } postfun(url,data){ return this.http.post(environment.baseurl+url,data,{ headers:new httpheaders({ 'content-type':'application/json' }) }) } getfun(url,data){ var params = qs.stringify(data); return this.http.get(environment.baseurl+url+'?'+params) }}
使用import { component, oninit } from '@angular/core';import {rxjsservice} from '../../services/rxjs.service';@component({ selector: 'app-rxjs', templateurl: './rxjs.component.html', styleurls: ['./rxjs.component.less']})export class rxjscomponent implements oninit { constructor(public rxjs:rxjsservice) { } ngoninit(): void { } getrxjs(){ this.rxjs.getfun('/api/school',{ name:'alice' }).subscribe((res)=>{ console.log(res); }) } postrxjs(){ this.rxjs.postfun('/api/info',{ name:'alice' }).subscribe((res)=>{ console.log(res); }) }}
更多编程相关知识,请访问:编程视频!!
以上就是浅谈angular中http请求模块的用法的详细内容。
