SoFunction
Updated on 2025-04-04

Angular data request implementation method

When using Angular to request data, the HttpModule module needs to be introduced. If you use jsonp mode, you need to introduce another JsonpModule module.

import { HttpModule, JsonpModule } from '@angular/http'

Then register in the imports in the current module

imports: [
 HttpModule,
 JsonpModule
],

After registration, you can introduce corresponding methods into the component file to make data requests.

import { Http, Jsonp } from '@angular/http'

Then it can be used after injecting it into the constructor of the current component.

constructor(private http: Http, private jsonp: Jsonp) { }

Use the following, a simple get request

// Inject and get the corresponding methodconstructor(private http: Http, private jsonp: Jsonp) { }
public list: any = []
// Request datagetData() {
 let url = 'http:///?a=getPortalList&catid=20&page=1'
 let _this = this
 (url).subscribe((data) => {
  _this.list = (data['_body'])['result']
  (_this.list)
 })
}

Just render it in the front desk

<button (click)="getData()">get Request data</button>
<ul>
 <li *ngFor="let item of list">
  {{}}
 </li>
</ul>

JSONP request data

Pay attention to the difference between the get request and use the following

// Request datajsonpData() {
 let url = 'http:///?a=getPortalList&catid=20&page=1&callback=JSONP_CALLBACK'
 let _this = this
 (url).subscribe((data) => {
  _this.list = data['_body']['result']
  (_this.list)
 })
}
// Rendering<button (click)="jsonpData()">jsonp Request data</button>
<ul>
 <li *ngFor="let item of list">
  {{}}
 </li>
</ul>

Differences

The specified callback function name must be added at the end of the requested url parameter &callback=JSONP_CALLBACK

The request method becomes (url)

The data format obtained after requesting is not unified and needs to be adjusted by yourself.

POST request

The request method is slightly different from GET. First, you need to introduce the request header { Headers }

import { Http, Jsonp, Headers } from '@angular/http'

Then define the request header, you need to instantiate the headers first

private headers = new Headers({'Content-Type': 'application/json'})

Finally, bring Headers when submitting the data

postData() {
 let url = 'http://localhost:8080/login'
 let data = {
  "username": "zhangsan",
  "password": "123"
 }
 (
  url,
  data,
  {headers: }
 ).subscribe((data) => {
  (data)
 })
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.