angular请求数据

app.module.ts中引入HttpClientModule

//jsonp请求 需引入 HttpClientJsonpModule
import {HttpClientModule,HttpClientJsonpModule} from "@angular/common/http";

@NgModule({
	imports:[
		BrowserModule,
		HttpClientModule,
		HttpClientJsonpModule, //jsonp请求 需引入
	]
})

在要使用的 组件.component.ts中引入HttpClient

import {Component,OnInit} from "@angular/core";
//引入请求的模块
import {HttpClient,HttpHeaders} from "@angular/common/http";

@Component({
	selector:'app-home',
	templateUrl:'./home.component.html',
	styleUrls:'./home.component.scss',
})
export class HomeComponent implements OnInit{
	constructor(public http:HttpClient){
		
	}
	ngOnInit(){

	}
	getData(){//get请求
		let url="xxxxxxx",
		this.http.get(url).subscribe((response)=>{
			console.log(response)
		})
	}
	postHttp(){//post 请求
		//手动设置请求类型
		const httpOptions={
			headers:new HttpHeaders({'Content-Type':'application/json'})
		}
		let url="xxxxxx";
		this.http.post(url,{username:'',id:''},httpOptions).subscribe((response)=>{
			console.log(response)
		})
	}
	jsonpData(){ //jsonp 请求
		//jsonp请求 服务器得支持jsonp
		//验证方法 http://xxxxxxx/xx?callback=xxx 在接口后面拼接callback=xxx 或 cb=xxxx (具体根据回调参数)
		let url='http://xxxxx/xxx'
		this.http.jsonp(url,'callback').subscribe((response)=>{
			console.log(response)
		})
	}
}


你可能感兴趣的:(angular,angular.js,前端)