This time I will bring you the implementation of angular data request. What are the precautions for the implementation of angular data request? The following is a practical case, let's take a look.
When using Angular to request data, you need to introduce the HttpModule module. If you use the jsonp mode, you need to introduce the JsonpModule module
import { HttpModule, JsonpModule } from '@angular/http'
and then in the current module Register within the imports
imports: [ HttpModule, JsonpModule ],
After registration, you can introduce the corresponding method in the component file to make data requests
import { Http, Jsonp } from '@angular/http'
Then in the constructor of the current component After injecting it, you can use it
constructor(private http: Http, private jsonp: Jsonp) { }
Use as follows, a simple get request
// 进行注入,拿到相对应的方法 constructor(private http: Http, private jsonp: Jsonp) { } public list: any = [] // 请求数据 getData() { let url = 'http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1' let _this = this this.http.get(url).subscribe((data) => { _this.list = JSON.parse(data['_body'])['result'] console.log(_this.list) }) }
Rendering in the frontend
<button (click)="getData()">get 请求数据</button> <ul> <li *ngFor="let item of list"> {{item.title}} </li> </ul>
JSONP request Data
Pay attention to the difference from the get request, use the following
// 请求数据 jsonpData() { let url = 'http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1&callback=JSONP_CALLBACK' let _this = this this.jsonp.get(url).subscribe((data) => { _this.list = data['_body']['result'] console.log(_this.list) }) }
// 渲染 <button (click)="jsonpData()">jsonp 请求数据</button> <ul> <li *ngFor="let item of list"> {{item.title}} </li> </ul>
Differences
The specified ## must be added at the end of the requested url parameter #Callback functionName&callback=JSONP_CALLBACK
The request method changes to this.jsonp.get(url)The data format obtained after the request is not uniform and needs to be adjusted by yourselfPOST request
The request method is slightly different from that of GET. First, you need to introduce the request header {Headers}import { Http, Jsonp, Headers } from '@angular/http'
private headers = new Headers({'Content-Type': 'application/json'})
postData() { let url = 'http://localhost:8080/login' let data = { "username": "zhangsan", "password": "123" } this.http.post( url, data, {headers: this.headers} ).subscribe((data) => { console.log(data) }) }
Detailed explanation of JS callback function use cases
PHP quick implementation of array deduplication method
The above is the detailed content of Angular data request implementation. For more information, please follow other related articles on the PHP Chinese website!