我创建了一项服务来处理所有 http 请求。它运行良好。但我想知道我的方法有什么问题,还想知道其他好的方法,比如 observable?
请求服务.js
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';
import { MessageService } from './message.service';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' })
};
interface IRequestOption {
url: string;
cxfgroup: string;
endpoint: string;
data: object;
}
interface IRequestBody {
option: IRequestOption;
log: string;
error: string;
}
class HTTP {
private messageService: MessageService;
constructor(http, messageService, url: string, body: object, log: string, error: string) {
this.callHTTP(http, url, body, log, error);
this.messageService = messageService;
}
callHTTP(http, url, body, log, error) {
return http.post(url, body, httpOptions).toPromise()
.then(this.extractData)
.catch(this.handleErrorPromise);
}
private extractData(res: Response) {
// let body = res.json();
// return body['data'] || {};
return res || {};
}
private handleErrorPromise(error: Response | any) {
console.error(error.message || error);
return Promise.reject(error.message || error);
}
}
class RequestFactory {
private baseURL = 'https://app.domain.com/cxf/';
/**
* CXF ENPOINTS
*/
private endpoints: any = {
"auth": {
"getcustomerkeys": "auth/getcustomerkeys"
}
};
call(http, messageService, options: IRequestOption, log: string, error: string) {
let url: string = options.url ? options.url : this.baseURL;
if (this.endpoints.hasOwnProperty(options['cxfgroup'])) {
url += this.endpoints[options.cxfgroup][options.endpoint];
}
return new HTTP(http, messageService, url, options.data, log, error);
}
}
@Injectable()
export class RequestService {
constructor(private http: HttpClient, private messageService: MessageService) { }
post(request: IRequestBody) {
let requestFactory = new RequestFactory();
requestFactory.call(this.http, this.messageService, request.option, request.log, request.error);
}
}
我正在使用以下代码调用此“发布”方法。在这里,我想在请求完成后设置一个承诺,我想显示一些消息。
this.requestService.post({
option: {
url: '',
cxfgroup: 'auth',
endpoint: 'getcustomerkeys',
data: {
userid: 'user@domain.com'
}
},
log: 'login initiated!',
error: 'customerKeyError'
});