Skip to content
This repository was archived by the owner on Feb 16, 2021. It is now read-only.
This repository was archived by the owner on Feb 16, 2021. It is now read-only.

Help needed #22

@ghost

Description

@voliva I need some help understanding how to handle responses, how to implement the interceptors with a component showing a loading ..?

I've successfully added an interceptor that adds some headers and sets the correct url to the request:

export function interceptorFactory(xhrBackend: XHRBackend,
                                   requestOptions: RequestOptions,
                                   baseInterceptor: BaseInterceptor)
{
	let service = new InterceptorService(xhrBackend, requestOptions);
	
	service.addInterceptor(baseInterceptor);
	
	return service;
}
export class BaseInterceptor implements Interceptor
{
	interceptBefore(request: InterceptedRequest): Observable<InterceptedRequest>|InterceptedRequest
	{
		/*
		 * Set request url
		 */
		let path: string = request.options.url;
		request.options.url = environment.apiUrl + path;
		
		/*
		 * Set api auth and allow cookies to be sent
		 */
		request.options.headers.set("api_token", "xxx");
		request.options.withCredentials = true;
		
		/*
		 * If POST then parse data and build the body
		 */
		if (request.options.method == RequestMethod.Post)
		{
			request.options.headers.set("Content-Type", "application/x-www-form-urlencoded");
			let urlSearchParams = new URLSearchParams();
			let body = request.options.body;
			for (let key in body)
			{
				urlSearchParams.append(key, request.options.body[key]);
			}
			request.options.body = urlSearchParams.toString();
		}
		
		return null;
	}
}

I'd like to set an interceptAfter to parse my response and return appropriate information:

interceptAfter(response: InterceptedResponse): Observable<InterceptedResponse>|InterceptedResponse
	{
		let res = response.response.json();
		switch (res.status)
		{
			case "error":
			{
				return Observable.throw(res.reason);
			}
			case "success":
			{
				return Observable.of(res.data);
			}
			default:
			{
				return Observable.throw("!!!! INVALID RESPONSE STATUS !!!!!");
			}
		}
	}

But with this code I get an error: TypeError: Cannot read property 'ok' of undefined because I'm not returning a response object but a certain imformation.

I know I'm doing something wrong, but how should I achieve my usecase with the interceptors?
And how should I use an interceptor inside my component to get events for showing/hiding a loading??

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions