모든 http 요청을 처리 할 수있는 서비스를 만들었습니다. 그것은 완벽하게 작동합니다. 그러나 나는 내 접근법에 어떤 잘못이 있는지를 알고 싶다. 또한 관찰 할 수있는 다른 좋은 접근법을 알고 싶다.http 요청 서비스를 만드는 가장 좋은 방법은 무엇입니까?
request.service.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);
}
}
는 다음 코드를 사용하여이 "POST"메소드를 호출하고 있습니다. 여기에 메시지를 표시하고 싶습니다. 요청이 완료되면 약속을 설정하겠습니다. 메시지를 표시하고 싶습니다.
this.requestService.post({
option: {
url: '',
cxfgroup: 'auth',
endpoint: 'getcustomerkeys',
data: {
userid: '[email protected]'
}
},
log: 'login initiated!',
error: 'customerKeyError'
});
이에서보세요 [** 답변 **] (HTTPS를 주입하는 데 사용할 수 있습니다
: 그리고
@NgModule
에서 인터셉터를 포함하는 것을 잊지 마세요 /stackoverflow.com/questions/43305876/set-global-data-to-property-from-get-request-before-continue/43307401#43307401) – Aravind