我想创建一个http拦截器来修改从日期时间到日期的http get返回的所有日期值,删除时间部分。
以下代码正在response["_body"]
进行搜索和替换,以替换DateTime并删除时间部分,但我不确定如何修改convertDateTimeToDate()
内的响应,以便响应中返回更改。您可以修改响应,以便将日期时间值替换为日期值吗?谢谢你的帮助。
通过Web API返回的JSON是一个数组employee[]
,其中每条记录如下所示:
{ "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" }
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 {
}
}
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();
}
}
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 {
}
答案 0 :(得分:1)
您应该在服务中使用私有方法来处理此问题,如下所示
private stripTime(temp:User[]):User[]{
temp.forEach(item=>{
item.birthDate = new Date(item.birthDate).toISOString().slice(0,10).replace(/-/g,"");;
}))
return temp;
}
<强> LIVE DEMO 强>