Angular6的升级,略有影响的地方应该主要集中在Rxjs6,而至于http,在Angular4.3之后就发生了变化。
rxjs6主要在包的结构/pipe的使用方式/API的重命名这几点与旧版本的使用方式不相容的变更,所以导致在实际使用中,有如下的变化
旧版 | 新版(4.3之后) |
---|---|
Http | HttpClient |
Response | HttpResponse |
Request | HttpRequest |
Headers | HttpHeaders |
import类型 | 旧版方式 | 新版方式(rxjs6) |
---|---|---|
Observable | import { Observable } from ‘rxjs/observable’ | import { Observable } from ‘rxjs’ |
map | import ‘rxjs/add/operator/map’ | import { map } from ‘rxjs/operators’ |
fromPromise | import ‘rxjs/add/observable/fromPromise’ |
import { fromPromise } from ‘rxjs’ |
angular的调用可以简单分为使用Http提供的服务取得Observable的返回值,根据Observable的返回值进行subscribe操作两段,这里也简单地整理一下两种方式下的使用方法的不同
http为@angular/http下的Http
this.http.get(url).map(response: Response) => {
response.json().xxxx进行引用
}
http为@angular/common/http下的HttpClient
this.http.get(url).pipe(map(item => item['xxxxxx']));
}
http为@angular/http下的Http
headers = new Headers({'Content-type': 'application/json'});
this.http.put(url, JSON.stringify(body),{headers: headers}).map((response: Response) => {
response.json.xxxxx进行引用
})
http为@angular/common/http下的HttpClient
headers = new HttpHeaders({'Content-type': 'application/json'});
this.http.put(url)put(url, JSON.stringify(body),{headers: headers}).pipe(map(item => {
item['xxxxxx']引用
}));
}
http为@angular/http下的Http
this.http.delete(url).map(response: Response) => {
response.json().xxxx进行引用
}
http为@angular/common/http下的HttpClient
this.http.delete(url).pipe(map(item => item['xxxxxx']));
}
Observable值
.subscribe(respose => {
使用response进行引用
})
import { HttpModule} from '@angular/http';
imports: [
...,
HttpModule,
...
],
import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent, combineLatest, SubscriptionLike, PartialObserver,concat,combineLatest } from 'rxjs';
import { map, filter, scan } from 'rxjs/operators';
import { webSocket } from 'rxjs/webSocket';
import { ajax } from 'rxjs/ajax';
import { TestScheduler } from 'rxjs/testing';
var url = "http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1"
this.http.get(url).pipe(map(res => res.json())).subscribe((data)=>{
console.log(data.result);
});
切记不要使用最新版本的@angular/common/http下的HttpClient,否则json转义会报如图所述错误: