1

I would like to create an http interceptor that modifies all date values returned from an http get from datetime to just date, removing the time portion.

The code below is doing a search and replace on the response["_body"] to replace DateTime and removing the Time portion, but I'm not sure how to modify the response within convertDateTimeToDate() so that the changes are returned in the response. Can you modify the response so that the datetime values are replaced with date values? Thanks for any help.

The JSON being returned via Web API is an array employee[] where each record looks like the following:

{ "employeeID":1, "firstName":"Nancy", "lastName":"Davolio", 
"title":"Sales Representative", "birthDate":"1948-12-08T00:00:00",
"hireDate":"1992-05-01T00:00:00", "city":"Seattle", "region":"WA", 
"postalCode":"98122", "country":"USA", "homePhone":"(206) 555-9857",
"extension":"5467" }

http-interceptor.service.ts

import { Injectable } from '@angular/core';

import {
    Http,
    ConnectionBackend,
    RequestOptions,
    RequestOptionsArgs,
    Request,
    Response,
    Headers
} from '@angular/http';

import { Observable } from 'rxjs/Observable';

import 'rxjs/Rx';

@Injectable()
export class HttpInterceptor extends Http
{
    constructor(
        backend: ConnectionBackend,
        defaultOptions: RequestOptions,
    ) {
        super(backend, defaultOptions);
    }

    /**
     * Performs a request with http get method.
     * @param url
     * @param options
     * @returns {Observable<>}
     */
    get(url: string, options?: RequestOptionsArgs): Observable<any> {
        this.beforeRequest();
        return super.get(url, this.requestOptions(options))
            .catch(this.onCatch)
            .do((res: Response) => {
                res = this.onSuccess(res);
            }, (error: any) => {
                this.onError(error);
            })
            .finally(() => {
                this.onFinally();
            });
    }

    //
    // Implement POST, PUT, DELETE HERE
    //

    /**
     * Request options.
     * @param options
     * @returns {RequestOptionsArgs}
     */
    private requestOptions(options?: RequestOptionsArgs): RequestOptionsArgs {
        if (options == null) {
            options = new RequestOptions();
        }
        if (options.headers == null) {
            options.headers = new Headers({
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            });
        }
        return options;
    }

    regexdatetime: RegExp = /T\d{2}:\d{2}:\d{2}/g;  // YYYY-MM-DDT24:00:00

    private convertDateTimeToDate(input) {
        // Ignore things that aren't objects.
        //if (typeof input !== "object") return input;

        //if (input["_body"] != null)
        //console.log("_body: " + input["_body"]);
        var value = input["_body"];
        var newvalue = value.replace(this.regexdatetime, "");
        //console.log("_body replace: " + newvalue);
        input["_body"] = newvalue;
        return input;
    }


    /**
     * Error handler.
     * @param error
     * @param caught
     * @returns {ErrorObservable}
     */
    private onCatch(error: any, caught: Observable<any>): Observable<any> {
        return Observable.throw(error);
    }

    /**
     * onSuccess
     * @param res
     */
    private onSuccess(res: Response): Response {
        //console.log(this.constructor.name + ".onSuccess " + res);
        return this.convertDateTimeToDate(res);
    }

    /**
     * onError
     * @param error
     */
    private onError(error: any): void {
    }

    /**
     * onFinally
     */
    private onFinally(): void {
    }
}

employee-list.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { Employee } from './employee';
import { EmployeeService } from './employee.service';

@Component({
    selector: 'employee-list',
    templateUrl: './employee-list.component.html',
})
export class EmployeeListComponent implements OnInit {
    title = 'Northwind Employees';
    employees: Employee[];
    isLoading: boolean = false;
    selectedEmployee: Employee;
    errorMessage: string;

    // dependency injection
    constructor(
        private _router: Router,
        private _service: EmployeeService
    ) { }

    getEmployees(): void {
        this.isLoading = true;
        this._service.getEmployees()
            .then((employees) =>
            {
                this.employees = employees;
                console.log(this.toString());
                this.isLoading = false;
            },
                error => this.errorMessage = <any>error
            )
    }

    ngOnInit(): void {
        this.getEmployees();
    }
}

app.module.ts

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

import { Http, HttpModule, XHRBackend, RequestOptions } from '@angular/http';
import { HttpInterceptor } from './http-interceptor.service';

import { UniversalModule } from 'angular2-universal';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './components/app/app.component'

import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';

import { NorthwindModule } from './components/northwind/northwind.module';

@NgModule({
    declarations: [
        AppComponent,
        NavMenuComponent,
        HomeComponent
    ],
    bootstrap: [ AppComponent ],
    providers: [
        {
            provide: Http,
            useClass: HttpInterceptor,
            useFactory: (backend: XHRBackend, options: RequestOptions) => {
                return new HttpInterceptor(backend, options);
            },
            deps: [ XHRBackend, RequestOptions ]
        }
    ],
    imports: [
        // Must be first import. 
        // This automatically imports BrowserModule, HttpModule, and JsonpModule too.
        UniversalModule,
        CommonModule,
        FormsModule,
        HttpModule,
        AppRoutingModule
    ]
})

export class AppModule {
}
2
  • It is working now. I figured it out. Commented Apr 12, 2017 at 22:23
  • Could you post your solution ? Commented Jun 22, 2017 at 9:15

1 Answer 1

1

You should be using a private method inside your service to handle this as below

private stripTime(temp:User[]):User[]{
      temp.forEach(item=>{
          item.birthDate = new Date(item.birthDate).toISOString().slice(0,10).replace(/-/g,"");;
      }))
      return temp;

   }

LIVE DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

If I try that approach I get back a DateTime value. I only want a date so it will display properly with <input type="date" ... BTW toISOString() isn't a valid function for my environment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.