实现网络请求方法汇总
1.创建service,提供公共方法,模拟网络请求
import { Injectable } from '@angular/core' ;
import { Observable} from "rxjs" ;
@Injectable ( {
providedIn: 'root'
} )
export class RequestService {
public data: string = "张三" ;
constructor ( ) { }
run ( ) {
return this . data
}
getCallbackData ( cb: any ) {
setTimeout ( ( ) => {
cb ( this . data)
} , 2000 )
}
getPromiseData ( ) {
return new Promise ( ( resolve, reject ) => {
setTimeout ( ( ) => {
resolve ( this . data) ;
} , 2000 )
} )
}
getRxjsData ( ) {
return new Observable ( observer => {
setTimeout ( ( ) => {
observer. next ( this . data) ;
} , 2000 )
} )
}
getPromiseIntervalData ( ) {
return new Promise ( ( resolve ) => {
setInterval ( ( ) => {
resolve ( this . data) ;
} , 2000 )
} )
}
getRxjsIntervalData ( ) {
return new Observable ( observer => {
let count = 0 ;
setInterval ( ( ) => {
observer. next ( this . data + count++ ) ;
} , 2000 )
} )
}
}
2.创建网络请求
使用callback
this . requestService. getCallbackData ( ( data: any ) => {
console. log ( "callback---" , data) ;
} )
使用promise
this . requestService. getPromiseData ( ) . then ( res => {
console. log ( "promise---" , res) ;
} )
使用rxjs
this . requestService. getRxjsData ( ) . subscribe ( res => {
console. log ( "rxjs---" , res) ;
} )
使用rxjs撤销数据请求
let d = this . requestService. getRxjsData ( ) . subscribe ( res => {
console. log ( "rxjs---撤销" , res) ;
} ) ;
setTimeout ( ( ) => {
d. unsubscribe ( ) ;
} , 1000 ) ;
使用promise不能一直请求数据
this . requestService. getPromiseIntervalData ( ) . then ( res => {
console. log ( "promiseInterval---" , res) ;
} )
使用rxjs可以一直请求数据
this . requestService. getRxjsIntervalData ( ) . subscribe ( res => {
console. log ( "rxjsInterval---" , res) ;
} )
以上方法全部执行打印
使用HttpClient获取网络数据
import { HttpClient, HttpHeaders} from '@angular/common/http'
constructor ( public http: HttpClient ) { }
HttpClient直接get请求
getData ( ) {
console. log ( "执行get请求" ) ;
let api = "http://a.itying.com/api/productlist"
this . http. get ( api) . subscribe ( ( res: any ) => {
this . list= res. result;
} ) ;
}
HttpClient直接post请求
postData ( ) {
const httpOptions = { headers: new HttpHeaders ( { 'Content-type' : 'application/json' } ) }
let api = 'https://www.baidu.com/?tn=62095104_43_oem_dg'
this . http. post ( api, { userName: '' } , httpOptions) . subscribe ( res => {
} )
console. log ( "执行post请求" ) ;
}
HttpClient/jsonp进行数据请求
getJsonp ( ) {
let api = "http://a.itying.com/api/productlist"
this . http. jsonp ( api, 'callback' ) . subscribe ( ( res: any ) => {
this . list= res. result;
} )
}
使用promise/axios进行数据请求
axiosGet ( api: any ) {
return new Promise ( ( resolve, reject ) => {
axios. get ( api) . then ( res => {
console. log ( res) ;
resolve ( res. data) ;
} )
} )
getAxios ( ) {
let api = "http://a.itying.com/api/productlist"
this . axiosGet ( api) . then ( ( res: any ) => {
this . list= res. result;
} )
}