简体   繁体   中英

JSON.parse - Set reviver once for all

In my Angular 2 application I need to parse some JSON strings that contain old ASP.NET dates, for instance /Date(1497984415000-0500)/ (I receive them from a WCF service).

I know I can use JSON.parse with a reviver parameter , but I need to do that many times in many pages of my web application so I would like to set the reviver once for all.

How can I achieve that?

You can do that with sending all functions with pipe function like this.

 postMethods(url:any,data:any) :Observable<Response>{

       let headers = new Headers();
        headers.append('Content-Type', 'application/json');  

      return this.http.post(`${API_URL+url}`,JSON.stringify(data),{headers:headers})
            .map((res:Response)=>{

              return this.dateConverter(res.json());})
            .catch((error:any)=>{
                return Observable.throw(error)||'server error';});
       }


 dateConverter(date){
    return new Date(date);
  }

You may have many api method like below.And you can call the above function to send request.

 testMethod(data){
      return this.postMethods('/setting/ChangePassword',data)
            .map(res=>{
              return res;
            });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM