1

모든 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' 
}); 
+1

이에서보세요 [** 답변 **] (HTTPS를 주입하는 데 사용할 수 있습니다

@NgModule({ providers: [ErrorHttpInterceptor] }) 

: 그리고 @NgModule에서 인터셉터를 포함하는 것을 잊지 마세요 /stackoverflow.com/questions/43305876/set-global-data-to-property-from-get-request-before-continue/43307401#43307401) – Aravind

답변

1

죄송 반응시켜 인 시츄 제조, 그것은 당신의 코드보다 모두 더 "간단한"입니다. 클래스, 클래스 및 클래스를 만들 필요가 없습니다. 더 좋은 방법은 항상 Observable을 반환하는 것입니다. 실제로 관측 가능하지 않고 약속을 사용하는 이점이 없습니다. 당신은 관찰을 반환하면 할 수 있습니다 "체인"(사용 포크), "그룹"(switchMap 사용) 등

@Injectable() 
export class RequestService { 
    private baseURL = 'https://app.domain.com/cxf/'; 
    constructor(private http: HttpClient) 

    post(request: IRequestBody) { 
     let url: string = options.url ? options.url : this.baseURL; 
     if (this.endpoints.hasOwnProperty(options['cxfgroup'])) { 
      url += this.endpoints[options.cxfgroup][options.endpoint]; 
     } 
     let requestFactory = new RequestFactory(); 
     this.http.post(url,this.messageService, request.option) 
     .do(console.log(request.log)) //when the request sucesfully 
             //show in console 
     .catch(console.log(request.error)); //if fail, show in console the error 
    } 
} 
+0

응답 해 주셔서 감사합니다. 미안 해요,하지만 게시물 등 다른 방법을 가지고 등 .. 어쨌든 그 코드를 분리해야합니다. –

+0

@Libu Mathew, 코드에서 다른 방법을 볼 수 없습니다. ( – Eliseo

+0

예.하지만이 모든 사례가 필요합니다. 코드가 분리 된 이유는 –

1

HTTP 서비스 다음은

는 우리가 사용하고있는 관측 기반의 접근 방식입니다 우리의 프로젝트 : 서비스

에서

import { Injectable } from '@angular/core'; 
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http'; 
import { Observable } from 'rxjs/Observable'; 

@Injectable() 
export class HttpService { 
    constructor(private http: HttpClient) {} 

    /** 
    * Invoke function should be able to handle any HTTP request based on the @params 
    */ 
    invoke(params): Observable<any> { 
    if (params) { 
     const method = params.method.toLowerCase(); 
     const { url, path, body, headers, query } = params; 

     const requestURL = `${url}/${path}`; 

     let request; 
     let requestParams = new HttpParams(); 
     let requestHeaders = new HttpHeaders(); 

     /** 
     * DEFAULT HEADERS 
     */ 
     requestHeaders = requestHeaders.set('Content-Type', 'application/json'); 

     /** 
     * CUSTOM HEADERS 
     */ 
     if (headers) { 
     for (const key in headers) { 
      if (headers.hasOwnProperty(key)) { 
      requestHeaders = requestHeaders.append(key, headers[key]); 
      } 
     } 
     } 

     /** 
     * CUSTOM REQUEST QUERY (?key=value) 
     */ 
     if (query) { 
     for (const key in query) { 
      if (query.hasOwnProperty(key)) { 
      requestParams = requestParams.append(key, query[key]); 
      } 
     } 
     } 

     const requestOptions = { 
     headers: requestHeaders, 
     params: requestParams, 
     }; 

     /** 
     * HANDLE GET, POST etc. REQUESTS 
     */ 
     if (method === 'get') { 
     request = this.http[method](requestURL, requestOptions); 
     } else if (method === 'post' || method === 'put') { 
     request = this.http[method](
      requestURL, 
      JSON.stringify(body), 
      requestOptions, 
     ); 
     } else if (method === 'delete') { 
     request = this.http.request(method, requestURL, { 
      ...requestOptions, 
      body: JSON.stringify(body), 
     }); 
     } else { 
     console.error('Unknown request method.'); 
     } 

     /** 
     * RETURN API REQUEST 
     */ 
     return request; 
    } 
    } 
} 

사용 예는 매우 심이다 PLE는 서비스에 사용하는, 그래서 거 같이 보일 것 :

constructor(private http: HttpService) {} 

makeRequest() { 
    return this.http.invoke({ 
    method: 'POST', // method like POST, GET etc. 
    url: 'http://blabla', // base URL 
    path: 'makeReq', // API endpoint 
    body: ..., // body for POST or PUT requests 
    headers: {headerName: 'HeaderValue'} // headers you need to add to your request 
    query: {query: 'queryValue'} // URL query to be added (eg. ?query=queryValue) 
    }); 
} 

body, headersquery는 선택적주의하시기 바랍니다. 구성 요소

그리고 마지막으로, 당신이 요청을 확인하기 위해 구성 요소에 관찰 가능한에 가입 할 필요가있는

사용 예 :

this.yourServiceName.makeRequest().subscribe(
    success => { 
    // handle success 
    }, 
    error => { 
    // handle error 
    } 
); 

오류 우리가 할 수있는 오류를 처리하기 위해

처리 HttpInterceptor을 사용하면 다음과 같이 표시됩니다.

import { Injectable } from '@angular/core'; 
import { 
    HttpEvent, 
    HttpInterceptor, 
    HttpHandler, 
    HttpRequest, 
    HttpErrorResponse, 
    HTTP_INTERCEPTORS, 
} from '@angular/common/http'; 
import { Observable } from 'rxjs/Observable'; 
import { _throw } from 'rxjs/observable/throw'; 
import 'rxjs/add/operator/catch'; 

@Injectable() 
export class ErrorInterceptor implements HttpInterceptor { 
    intercept(
    req: HttpRequest<any>, 
    next: HttpHandler, 
): Observable<HttpEvent<any>> { 
    return next.handle(req).catch(errorReponse => { 
     let error: string; 
     if (errorReponse instanceof HttpErrorResponse) { 
     error = errorReponse.error; 
     const { status, statusText, message } = errorReponse; 
     const errMsg = `HTTP ERROR: ${status} - ${statusText}\n${message}\n\nBACKEND RESPONSE: `; 
     console.error(errMsg, error); 
     } else { 
     error = null; 
     } 
     return _throw(error); 
    }); 
    } 
} 

export const ErrorHttpInterceptor = { 
    provide: HTTP_INTERCEPTORS, 
    useClass: ErrorInterceptor, 
    multi: true, 
}; 

HttpInterceptorHttpClient 제공자가 만든 모든 HTTP 호출에 일부 미들웨어 기능을 적용합니다. 최신 버전에서는 더 이상 제공되지 않으므로 Http 제공자와 호환되지 않습니다./: 비슷한 접근 방식 등 Authorization 토큰