Migrate from http module to httpClient module

This commit is contained in:
Baron Chen 2018-05-14 21:39:45 +10:00
parent 4eb73f8e23
commit fc9c9ff65a
9 changed files with 77 additions and 84 deletions

View File

@ -1,7 +1,7 @@
import { NgModule, NgModuleFactoryLoader } from '@angular/core'; import { NgModule, NgModuleFactoryLoader } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser'; import { BrowserModule } from '@angular/platform-browser';
// import { FormsModule } from '@angular/forms'; // import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http'; import { HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router'; import { RouterModule } from '@angular/router';
import { routing } from './app.routes'; import { routing } from './app.routes';
@ -18,7 +18,7 @@ import { CampaignsModule } from './campaigns/campaigns.module';
imports: [ imports: [
BrowserModule, BrowserModule,
routing, routing,
HttpModule, HttpClientModule,
// Only module that app module loads // Only module that app module loads
SharedModule.forRoot(), SharedModule.forRoot(),
CatalogModule, CatalogModule,

View File

@ -1,5 +1,5 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { Response, Headers } from '@angular/http'; import { HttpResponse, HttpHeaders } from '@angular/common/http';
import { Router } from '@angular/router'; import { Router } from '@angular/router';
import { DataService } from '../shared/services/data.service'; import { DataService } from '../shared/services/data.service';
@ -68,14 +68,14 @@ export class BasketService {
setBasket(basket): Observable<boolean> { setBasket(basket): Observable<boolean> {
let url = this.purchaseUrl + '/api/v1/basket/'; let url = this.purchaseUrl + '/api/v1/basket/';
this.basket = basket; this.basket = basket;
return this.service.post(url, basket).map((response: Response) => { return this.service.post<Object>(url, basket).map((response: HttpResponse<Object>) => {
return true; return true;
}); });
} }
setBasketCheckout(basketCheckout): Observable<boolean> { setBasketCheckout(basketCheckout): Observable<boolean> {
let url = this.basketUrl + '/api/v1/b/basket/checkout'; let url = this.basketUrl + '/api/v1/b/basket/checkout';
return this.service.postWithId(url, basketCheckout).map((response: Response) => { return this.service.postWithId<Object>(url, basketCheckout).map((response: HttpResponse<Object>) => {
this.basketEvents.orderCreated(); this.basketEvents.orderCreated();
return true; return true;
}); });
@ -83,12 +83,12 @@ export class BasketService {
getBasket(): Observable<IBasket> { getBasket(): Observable<IBasket> {
let url = this.basketUrl + '/api/v1/b/basket/' + this.basket.buyerId; let url = this.basketUrl + '/api/v1/b/basket/' + this.basket.buyerId;
return this.service.get(url).map((response: Response) => { return this.service.get<IBasket>(url).map((response: HttpResponse<IBasket>) => {
if (response.status === 204) { if (response.status === 204) {
return null; return null;
} }
return response.json(); return response.body;
}); });
} }

View File

@ -1,5 +1,5 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { Response } from '@angular/http'; import { HttpResponse } from '@angular/common/http';
import { DataService } from '../shared/services/data.service'; import { DataService } from '../shared/services/data.service';
import { ICampaign } from '../shared/models/campaign.model'; import { ICampaign } from '../shared/models/campaign.model';
@ -36,16 +36,16 @@ export class CampaignsService {
let url = this.marketingUrl + '/api/v1/m/campaigns/user'; let url = this.marketingUrl + '/api/v1/m/campaigns/user';
url = url + '?pageIndex=' + pageIndex + '&pageSize=' + pageSize; url = url + '?pageIndex=' + pageIndex + '&pageSize=' + pageSize;
return this.service.get(url).map((response: Response) => { return this.service.get<ICampaign>(url).map((response: HttpResponse<ICampaign>) => {
return response.json(); return response.body;
}); });
} }
getCampaign(id: number): Observable<ICampaignItem> { getCampaign(id: number): Observable<ICampaignItem> {
let url = this.marketingUrl + '/api/v1/m/campaigns/' + id; let url = this.marketingUrl + '/api/v1/m/campaigns/' + id;
return this.service.get(url).map((response: Response) => { return this.service.get<ICampaignItem>(url).map((response: HttpResponse<ICampaignItem>) => {
return response.json(); return response.body;
}); });
} }
} }

View File

@ -1,5 +1,5 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { Response } from '@angular/http'; import { HttpResponse } from '@angular/common/http';
import { DataService } from '../shared/services/data.service'; import { DataService } from '../shared/services/data.service';
import { ConfigurationService } from '../shared/services/configuration.service'; import { ConfigurationService } from '../shared/services/configuration.service';
@ -35,20 +35,20 @@ export class CatalogService {
url = url + '?pageIndex=' + pageIndex + '&pageSize=' + pageSize; url = url + '?pageIndex=' + pageIndex + '&pageSize=' + pageSize;
return this.service.get(url).map((response: Response) => { return this.service.get<ICatalog>(url).map((response: HttpResponse<ICatalog>) => {
return response.json(); return response.body;
}); });
} }
getBrands(): Observable<ICatalogBrand[]> { getBrands(): Observable<ICatalogBrand[]> {
return this.service.get(this.brandUrl).map((response: Response) => { return this.service.get<ICatalogBrand[]>(this.brandUrl).map((response: HttpResponse<ICatalogBrand[]>) => {
return response.json(); return response.body;
}); });
} }
getTypes(): Observable<ICatalogType[]> { getTypes(): Observable<ICatalogType[]> {
return this.service.get(this.typesUrl).map((response: Response) => { return this.service.get<ICatalogType[]>(this.typesUrl).map((response: HttpResponse<ICatalogType[]>) => {
return response.json(); return response.body;
}); });
}; };
} }

View File

@ -1,5 +1,5 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { Response } from '@angular/http'; import { HttpResponse } from '@angular/common/http';
import { DataService } from '../shared/services/data.service'; import { DataService } from '../shared/services/data.service';
import { IOrder } from '../shared/models/order.model'; import { IOrder } from '../shared/models/order.model';
@ -31,16 +31,16 @@ export class OrdersService {
getOrders(): Observable<IOrder[]> { getOrders(): Observable<IOrder[]> {
let url = this.ordersUrl + '/api/v1/o/orders'; let url = this.ordersUrl + '/api/v1/o/orders';
return this.service.get(url).map((response: Response) => { return this.service.get<IOrder[]>(url).map((response: HttpResponse<IOrder[]>) => {
return response.json(); return response.body;
}); });
} }
getOrder(id: number): Observable<IOrderDetail> { getOrder(id: number): Observable<IOrderDetail> {
let url = this.ordersUrl + '/api/v1/o/orders/' + id; let url = this.ordersUrl + '/api/v1/o/orders/' + id;
return this.service.get(url).map((response: Response) => { return this.service.get<IOrderDetail>(url).map((response: HttpResponse<IOrderDetail>) => {
return response.json(); return response.body;
}); });
} }

View File

@ -1,5 +1,5 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { Http, Response, RequestOptionsArgs, RequestMethod, Headers } from '@angular/http'; import { HttpClient, HttpResponse, HttpHeaders } from '@angular/common/http';
import { IConfiguration } from '../models/configuration.model'; import { IConfiguration } from '../models/configuration.model';
import { StorageService } from './storage.service'; import { StorageService } from './storage.service';
@ -19,14 +19,14 @@ export class ConfigurationService {
settingsLoaded$ = this.settingsLoadedSource.asObservable(); settingsLoaded$ = this.settingsLoadedSource.asObservable();
isReady: boolean = false; isReady: boolean = false;
constructor(private http: Http, private storageService: StorageService) { } constructor(private http: HttpClient, private storageService: StorageService) { }
load() { load() {
const baseURI = document.baseURI.endsWith('/') ? document.baseURI : `${document.baseURI}/`; const baseURI = document.baseURI.endsWith('/') ? document.baseURI : `${document.baseURI}/`;
let url = `${baseURI}Home/Configuration`; let url = `${baseURI}Home/Configuration`;
this.http.get(url).subscribe((response: Response) => { this.http.get(url).subscribe((data: IConfiguration) => {
console.log('server settings loaded'); console.log('server settings loaded');
this.serverSettings = response.json(); this.serverSettings = data;
console.log(this.serverSettings); console.log(this.serverSettings);
this.storageService.store('identityUrl', this.serverSettings.identityUrl); this.storageService.store('identityUrl', this.serverSettings.identityUrl);
this.storageService.store('marketingUrl', this.serverSettings.marketingUrl); this.storageService.store('marketingUrl', this.serverSettings.marketingUrl);

View File

@ -1,5 +1,5 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { Http, Response, RequestOptionsArgs, RequestMethod, Headers } from '@angular/http'; import { HttpClient, HttpHeaders, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import 'rxjs/Rx'; import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable'; import { Observable } from 'rxjs/Observable';
@ -15,96 +15,89 @@ import { Guid } from '../../../guid';
// is pending to do for the SPA app // is pending to do for the SPA app
@Injectable() @Injectable()
export class DataService { export class DataService {
constructor(private http: Http, private securityService: SecurityService) { } constructor(private http: HttpClient, private securityService: SecurityService) { }
get(url: string, params?: any): Observable<Response> { get<T>(url: string, params?: any): Observable<HttpResponse<T>> {
let options: RequestOptionsArgs = {}; let headers: HttpHeaders = new HttpHeaders();
if (this.securityService) { if (this.securityService) {
options.headers = new Headers(); headers = headers.set('Authorization', 'Bearer ' + this.securityService.GetToken());
options.headers.append('Authorization', 'Bearer ' + this.securityService.GetToken());
} }
return this.http.get(url, options).map( return this.http.get(url, {headers: headers, observe: "response"}).map(
(res: Response) => { (res: HttpResponse<T>) => res).catch(this.handleError);
return res;
}).catch(this.handleError);
} }
postWithId(url: string, data: any, params?: any): Observable<Response> { postWithId<T>(url: string, data: any, params?: any): Observable<HttpResponse<T>> {
return this.doPost(url, data, true, params); return this.doPost(url, data, true, params);
} }
post(url: string, data: any, params?: any): Observable<Response> { post<T>(url: string, data: any, params?: any): Observable<HttpResponse<T>> {
return this.doPost(url, data, false, params); return this.doPost(url, data, false, params);
} }
putWithId(url: string, data: any, params?: any): Observable<Response> { putWithId<T>(url: string, data: any, params?: any): Observable<HttpResponse<T>> {
return this.doPut(url, data, true, params); return this.doPut(url, data, true, params);
} }
private doPost(url: string, data: any, needId: boolean, params?: any): Observable<Response> { private doPost<T>(url: string, data: any, needId: boolean, params?: any): Observable<HttpResponse<T>> {
let options: RequestOptionsArgs = {}; let headers: HttpHeaders = new HttpHeaders();
options.headers = new Headers();
if (this.securityService) { if (this.securityService) {
options.headers.append('Authorization', 'Bearer ' + this.securityService.GetToken()); headers = headers.set('Authorization', 'Bearer ' + this.securityService.GetToken());
} }
if (needId) { if (needId) {
let guid = Guid.newGuid(); let guid = Guid.newGuid();
options.headers.append('x-requestid', guid); headers = headers.set('x-requestid', guid);
} }
return this.http.post(url, data, options).map( return this.http.post(url, data, {headers: headers, observe:'response'}).map(
(res: Response) => { (res: HttpResponse<T>) => {
return res; return res;
}).catch(this.handleError); }).catch(this.handleError);
} }
private doPut(url: string, data: any, needId: boolean, params?: any): Observable<Response> { private doPut<T>(url: string, data: any, needId: boolean, params?: any): Observable<HttpResponse<T>> {
let options: RequestOptionsArgs = {}; let headers: HttpHeaders = new HttpHeaders();
options.headers = new Headers();
if (this.securityService) { if (this.securityService) {
options.headers.append('Authorization', 'Bearer ' + this.securityService.GetToken()); headers = headers.set('Authorization', 'Bearer ' + this.securityService.GetToken());
} }
if (needId) { if (needId) {
let guid = Guid.newGuid(); let guid = Guid.newGuid();
options.headers.append('x-requestid', guid); headers = headers.set('x-requestid', guid);
} }
return this.http.put(url, data, options).map( return this.http.put(url, data, {headers: headers, observe: 'response'}).map(
(res: Response) => { (res: HttpResponse<T>) => {
return res; return res;
}).catch(this.handleError); }).catch(this.handleError);
} }
delete(url: string, params?: any) { delete(url: string, params?: any) {
let options: RequestOptionsArgs = {}; let headers: HttpHeaders = new HttpHeaders();
if (this.securityService) { if (this.securityService) {
options.headers = new Headers(); headers = headers.set('Authorization', 'Bearer ' + this.securityService.GetToken());
options.headers.append('Authorization', 'Bearer ' + this.securityService.GetToken());
} }
console.log('data.service deleting'); console.log('data.service deleting');
// return this.http.delete(url, options).subscribe(
// return res;
// );
this.http.delete(url, options).subscribe((res) => { this.http.delete(url, {headers: headers, observe: 'response'}).subscribe((res) => {
console.log('deleted'); console.log('deleted');
}); });
} }
private handleError(error: any) { private handleError(error: HttpErrorResponse) {
console.error('server error:', error); console.error('server error:', error);
if (error instanceof Response) { if (error.error instanceof Error) {
let errMessage = ''; let errMessage = '';
try { if (error.error.message && error.error.message !== '')
errMessage = error.json(); {
} catch (err) { errMessage = error.error.message;
errMessage = error.statusText; }
else
{
errMessage = error.status.toString();
} }
return Observable.throw(errMessage); return Observable.throw(errMessage);
} }

View File

@ -1,5 +1,5 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http'; import { HttpClient, HttpResponse, HttpHeaders } from '@angular/common/http';
import 'rxjs/add/operator/map'; import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable'; import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject'; import { Subject } from 'rxjs/Subject';
@ -12,16 +12,16 @@ import { StorageService } from './storage.service';
export class SecurityService { export class SecurityService {
private actionUrl: string; private actionUrl: string;
private headers: Headers; private headers: HttpHeaders;
private storage: StorageService; private storage: StorageService;
private authenticationSource = new Subject<boolean>(); private authenticationSource = new Subject<boolean>();
authenticationChallenge$ = this.authenticationSource.asObservable(); authenticationChallenge$ = this.authenticationSource.asObservable();
private authorityUrl = ''; private authorityUrl = '';
constructor(private _http: Http, private _router: Router, private route: ActivatedRoute, private _configurationService: ConfigurationService, private _storageService: StorageService) { constructor(private _http: HttpClient, private _router: Router, private route: ActivatedRoute, private _configurationService: ConfigurationService, private _storageService: StorageService) {
this.headers = new Headers(); this.headers = new HttpHeaders();
this.headers.append('Content-Type', 'application/json'); this.headers = this.headers.set('Content-Type', 'application/json');
this.headers.append('Accept', 'application/json'); this.headers = this.headers.set('Accept', 'application/json');
this.storage = _storageService; this.storage = _storageService;
this._configurationService.settingsLoaded$.subscribe(x => { this._configurationService.settingsLoaded$.subscribe(x => {
@ -224,21 +224,20 @@ export class SecurityService {
if (this.authorityUrl === '') if (this.authorityUrl === '')
this.authorityUrl = this.storage.retrieve('IdentityUrl'); this.authorityUrl = this.storage.retrieve('IdentityUrl');
return this._http.get(this.authorityUrl + '/connect/userinfo', { return this._http.get<string[]>(this.authorityUrl + '/connect/userinfo', {
headers: this.headers, headers: this.headers,
body: '' }).map(res => res);
}).map(res => res.json());
} }
private setHeaders() { private setHeaders() {
this.headers = new Headers(); this.headers = new HttpHeaders();
this.headers.append('Content-Type', 'application/json'); this.headers = this.headers.set('Content-Type', 'application/json');
this.headers.append('Accept', 'application/json'); this.headers = this.headers.set('Accept', 'application/json');
let token = this.GetToken(); let token = this.GetToken();
if (token !== '') { if (token !== '') {
this.headers.append('Authorization', 'Bearer ' + token); this.headers = this.headers.set('Authorization', 'Bearer ' + token);
} }
} }
} }

View File

@ -2,7 +2,8 @@ import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule, FormBuilder } from '@angular/forms'; import { FormsModule, ReactiveFormsModule, FormBuilder } from '@angular/forms';
import { RouterModule } from '@angular/router'; import { RouterModule } from '@angular/router';
import { HttpModule, JsonpModule } from '@angular/http'; import { JsonpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
// Services // Services
@ -29,7 +30,7 @@ import { UppercasePipe } from './pipes/uppercase.pipe';
RouterModule, RouterModule,
NgbModule.forRoot(), NgbModule.forRoot(),
// No need to export as these modules don't expose any components/directive etc' // No need to export as these modules don't expose any components/directive etc'
HttpModule, HttpClientModule,
JsonpModule JsonpModule
], ],
declarations: [ declarations: [