概括休息服务调用并将服务器响应映射到我的对象

问题描述 投票:0回答:1

我试图在我的所有服务中创建一个通用的休息服务,例如对于POST请求,我有这个代码

post<T>(relativeUrl: string, body?: any,  params?: HttpParams, headers?: HttpHeaders): Observable<HttpResponse<T>> {
        return this.executeRequest(this.createRequest(relativeUrl, body, params, headers, 'POST'))
    }

并以类似的方式用于其他HTTP请求方法。所有这些方法都调用createRequest和executeRequest

// TODO: Finish and check arguments
    private createRequest(relativeUrl: string, body: any, params: HttpParams | null, headers: HttpHeaders | null, method: string ): HttpRequest<any> {

        let url: string;
        if (relativeUrl.startsWith('http') || relativeUrl.startsWith('https')) {
            url = relativeUrl;
        } else {
            url = `${environment.restUrl}/${relativeUrl}`;
        }


        headers = headers || new HttpHeaders()
        //TODO: If user is logged add Authorization bearer in headers

        return new HttpRequest(method, url, body, {
            headers: headers,
            params: params
        })
    }

    private executeRequest(request: HttpRequest<any>): Observable<HttpResponse<any>> {
        return <any> this.http.request(request)
            .pipe(
                catchError(error => {
                    return throwError(error);
                })
            );
    }

这是正确的,因为我设置方法? HTTP请求方法的返回值是否正确?例如,在我的login.service中,我以这种方式使用POST方法

login<User>(email: string, password: string): Observable<HttpResponse<User>>{

        const data = {
            email: email,
            password: password
        };

        let headers = new HttpHeaders({
            'Content-Type':  'application/json',
            'Accept-Language': 'it'
        })

        return this.restService.post<User>(this.baseUrl, data, null, headers)
            .pipe(
                catchError(error => {
                    this.notificationService.error(error.error.error.message);
                    return throwError(error);
                })
            );
    }

我对从服务器和我的User对象返回的json转换的时间有所怀疑。当我使用loginService时,我应该在服务或组件中进行转换?我是如何进行这种转换的?这是正确的

Object.assign(new User(), serverResponse.body)

?

angular typescript
1个回答
1
投票

将相同逻辑应用于所有请求的正确方法是使用Http Interceptors。

Damien Bod在他的angular-auth-oidc-client库中有很好的例子

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    private oidcSecurityService: OidcSecurityService;

    constructor(private injector: Injector) {}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        let requestToForward = req;

        if (this.oidcSecurityService === undefined) {
            this.oidcSecurityService = this.injector.get(OidcSecurityService);
        }
        if (this.oidcSecurityService !== undefined) {
            let token = this.oidcSecurityService.getToken();
            if (token !== '') {
                let tokenValue = 'Bearer ' + token;
                requestToForward = req.clone({ setHeaders: { Authorization: tokenValue } });
            }
        } else {
            console.debug('OidcSecurityService undefined: NO auth header!');
        }

        return next.handle(requestToForward);
    }
}

REF:https://github.com/damienbod/angular-auth-oidc-client

© www.soinside.com 2019 - 2024. All rights reserved.