B
B
beta-it2018-06-25 16:07:30
Angular
beta-it, 2018-06-25 16:07:30

Result parsing in Angular 5+, how to?

Good day everyone.
Data comes from the server but wrapped in its own response format:

{
  success: boolean; // статус выполнения запроса
  data: any | null; //здесь может вернуться любой объект/массив объектов/null/пустые объект или массив
  msg: string | null; // текст ошибки либо null в случае успеха
}

Those. all data comes to data...
What I'm doing now:
I made an interface:
export interface IResponse<T> {
  success: boolean;
  data: T | null;
  msg: string | null;
}

And made a handler function:
getDataResponse<T>(response: IResponse<T>) {
    if (response && response.data) {
      return response.data;
    } else {
      return null;
    }
  }

Well, actually in the providers I call all this as follows:
/**
   * Получение информации об авторизованном пользователе
   * @param {number} id
   * @returns {Observable<IUser>}
   */
  public getUserInfo(id: number): Observable<IUser> {
    const url = `${env.url}/${id}/info`;

    return this.httpClient
      .get(url)
      .pipe(
        map((response: IResponse<IUser>) => this.getData(response))
      );
  }

How to deal with such a return from the server? Perhaps there is a better/correct solution?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Stroykin, 2018-06-25
@beta-it

Describe an Http Interceptor that will intercept the response, perform manipulations, and return it in the format you need. Examples can be found by googling: " angular 5 http interceptor response "

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question