0

I'M making an angular2 application and right now i'm trying to parse a string into a object. Basically what is happening is I'm passing back a string, and i want to convert it into a unique object called IDate. I get a string in this format "2017-02-27T00:00:00", but i want it as IDate(). So what i have done so far is created a IDate class, that takes a string and converts it to a date. I created a Mock class to map the response to an object. However, when i print the object, i see the value stays a string. Anyone know how to achieve what I'm talking about? I'm basically trying to map the string to an object when i map the response from the controller. I could do this in an operation like, resposne.map(r.time => new Date(r.time)); But i rather have it mapped in the response, because i call this controllers in other places and i dont want to repeat the process on separate pages. Can this be done?

Controller

        return Json(new { Number = 1, Time= "2017-02-27T00:00:00" });

Client

class IDate {
    value: Date; 
    contructor(value) {
        this.value = new Date(value); 
    }
}
class Mock {
    number: number;
    time: IDate;
}
mock: Mock = null; 

 this.service.get()
            .subscribe(
            response => {
                console.log("Test response");
                this.mock = response;
                console.log(this.mock);
            },

Console

Object
  number:1
  time:"2017-02-27T00:00:00"
  __proto__:Object
AJ_
  • 3,787
  • 10
  • 47
  • 82
  • That works if i passed an object in string format, im trying to pass a string and convert it into an object – AJ_ Mar 31 '17 at 16:02
  • Possible duplicate of [Difference between Date(dateString) and new Date(dateString)](http://stackoverflow.com/questions/3505693/difference-between-datedatestring-and-new-datedatestring) – Scott Marcus Mar 31 '17 at 16:04
  • @ScottMarcus Not what im trying to do, please read the question again and let me know if its not clear. – AJ_ Mar 31 '17 at 16:04
  • Looks like `constructor` is spelled wrong in your IDate class, not sure that's the issue though – kleaver Mar 31 '17 at 16:11
  • Maybe i should change this question to how to return date types – AJ_ Mar 31 '17 at 16:17

1 Answers1

0

I am assuming that you are getting a JSON string from your REST API. If this holds true for your case, you may use a reviver. Here is a simplistic approach to use the reviver:

JSON.parse(jsonString, function (key, value) {
    if (key === "time")
        return new Date(value);
    return value;
})

Here is the link to a running fiddle: https://jsfiddle.net/sayan751/Lzb8u638/.


Updated based on OP's comment

Converting a generic object to an instance of a specific class is not very straight forward. Note that this.mock = response; does not covert response to an instance of Mock class (refer the new fiddle link).

You may use Object.assign, but it might not work with type conversion.

Also I think in your case, the schema of the json object {Number:number, Time:string} received in your JavaScript code does not match with the schema of Mock:{number:number, time:{value:Date}}.

In this case, it would be best (as per my opinion) to write a custom converter for Mock. One simplistic approach can be as below. For detailed code, refer the new fiddle link.

class Mock {
    number: number;
    time: IDate;

    public static create(obj):Mock{
        let retVal = new Mock();
      retVal.number=obj.number;

      if(typeof obj.time === "string")
        retVal.time = new Date(obj.time); //better to use moment in this case, if possible
      else if(obj.time instanceof Date)
        retVal.time = obj.time;

      return retVal;
    }
}

var jsonObj = { number: 1, time: "2017-02-27T00:00:00" };

var obj = Mock.create(jsonObj);

Link to fiddle: https://jsfiddle.net/sayan751/mxoqqc5a/

Hope this helps.

Community
  • 1
  • 1
Sayan Pal
  • 4,768
  • 5
  • 43
  • 82
  • I'm getting a JSON object and it gets mapped to Mock class vai typescript, i would like the string data to be a date, but for some reason its not getting mapped to one. – AJ_ Apr 03 '17 at 19:09
  • I'm not instantiating the object, I'm trying to change the the value when it gets mapped, but i see you are saying that impossible. – AJ_ Apr 03 '17 at 21:30