Transform webservice data into TypeScript object format, ensuring mapping of objects from capital letters to camel case

Something peculiar caught my attention in my Angular2 TypeScript project. When objects are fetched from a web service, they have the type "Level" and the properties are in Pascal case. However, during runtime, I noticed that the properties of these Levels have lowercase letters in my TypeScript project (as seen in the browser's developer debug tool).

I believe I need to somehow map the JSON properties instead of using "as Level[]" for casting everywhere. How can I achieve this properly?

Update: In response to requests for code samples:

(Controller)

ngOnInit(): void {
    this.levelsObservable = this.levelsService.getAllLevels();
            this.levelsObservable.subscribe(
              data => console.log(data)
        );
  }

(Service)

observable : Observable<Response>;
getAllLevels(): Observable<Level[]> {
    this.observable =  this.achievementsService.getAllAchievements(this.allLevelsUrlPart);
    return this.observable
    .map((response: Response) => {
      const srcData = response.json() as Level[];
      return srcData;})
    .catch(error => this.handleError(error));}

getAllAchievements(detailPath): Observable<Response> {
// prepare request url and header
this.specificUrl = this.webServiceUrl + detailPath;
this.headers.append('Content-type', 'application/json');
let options = new RequestOptions({ headers: this.headers });
this.result = this.http.get(this.specificUrl, options)
.catch(error => this.handleError(error));
return this.result;}

Update: I made some improvements to my code with help from a previous answer (not included above as it does not address the main issue). I attempted to implement another suggestion to convert to camel case but encountered difficulties accessing object properties within an array.

Update: Success! After hours of searching, I finally found a solution (!). I've condensed this post and will share my solution below. It may not be perfect, but I'm grateful for all the helpful advice provided here!

Answer №1

If you want to retrieve the objects in lowercase, you can utilize this method.

  transformSourceData(srcData){
    let obj = {};
    Object.keys(srcData).forEach((key)=>{
      obj[key.lowerCaseFirstLetter()] = srcData[key];
    })
    return obj
  }
  String.prototype.lowerCaseFirstLetter = function() {
    return this.charAt(0).toLowerCase() + this.slice(1);
  }

You can then proceed to return the transformed data

getAllLevels(): Observable<Level[]> {
    this.observable =  this.achievementsService.getAllAchievements(this.allLevelsUrlPart);
    return this.observable
    .map((response: Response) => {
      const srcData = response.json() as Level[];
      return this.transformSourceData(srcData);})
    .catch(error => this.handleError(error));}

Answer №2

You've overcomplicated both methods. Simplify it as:

this.webServiceUrl = "http...."; // service endpoint
this.headers.append('Content-type', 'application/json');
let options = new RequestOptions({ headers: this.headers });

// Handle errors
private handleError(error: Response) {
        console.log(error);
        return Observable.throw(error.json().error || 'Internal Server error');
}   

Use TypeCasting in your service method like this:

getAllLevels(detailPath): Observable<Level[]> {
    return this.http.get(detailPath, options)
                  .map((response: Response) => <Level[]>response.json())
                  .catch(this.handleError);
}

The component should send the request to the service on initialization:

ngOnInit(): void{
        this._myService.getAllLevels()
                    .subscribe(levels => this.levels = levels,
                    error => this.errorMessage = <any> error);

}  

Declare variables like this:

levels: Level[];

Answer №3

After hours of hard work and research, I have finally found a solution! Although it may not be the most elegant one, it is easy to grasp and comprehend:

function extractLevelProperties(response: any): Level[] {
    let levels: Level[] = [];
     Object.keys(response).forEach((key) => {
       // Create a new object by extracting only the necessary information from the JSON data.
       // Since the webservice uses Pascal case letters, we need to convert them into camel case format.
      this.level = new Level(response[key]["AchievementId"], response[key]["Image"],
        response[key]["GrantedTo"], response[key]["GrantedBy"], response[key]["GrantedWhen"],  response[key]["Description"], 
        response[key]["Name"], response[key]["CompetitionCode"], response[key]["Number"]);

      levels[key] = this.level;
  });

     return levels;
  };

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to create a JsonPath query in C# using Newtonsoft Json.NET for a null property

Suppose we have a JSON array containing: [ { "id": 1, "name": "abc" }, { "id": 2 }, { "id": 3, "name": "def" } ] In this scenario, if we use th ...

Encountering the issue of receiving "undefined" when utilizing the http .get() method for the first time in Angular 2

When working in Angular, I am attempting to extract data from an endpoint. Below is the service code: export class VideosService { result; constructor(private http: Http, public router: Router) { } getVideos() { this.http.get('http://local ...

Converting an array of object values to an Interface type in Typescript

In my JSON document, I have an array named dealers that consists of various dealer objects like the examples below: "dealers" : [ { "name" : "BMW Dealer", "country" : "Belgium", "code" : "123" }, { "name" : ...

When attempting to use a jQuery-formatted JSON object within an <optgroup > returned via AJAX from PHP and MySQL, it appears to be incompatible with Select2

After spending an entire day attempting to create a PHP script that converts MySQL Query results into a JSON object for <optgroup> in Select2, I finally found a solution. However, when I implemented it, nothing appeared in the Select2 dropdown menu. ...

forwarding within afterCallback employing nextjs-auth0

I need to handle multiple cases for redirecting users based on various fields and custom claims in the user token, which involves navigating through complex if/else blocks. Let's consider a simpler example where I want to redirect the user to /email- ...

Using Docker to Deploy an Angular Frontend alongside a NodeJS/Express Backend

I recently created a web application using Angular for the frontend and NodeJS/Express for the backend. While everything is working smoothly locally, I encountered an issue when trying to move the application to Docker containers. The problem arises with ...

Ensuring TypeScript's strict null check on a field within an object that is part of an

When using TypeScript and checking for null on a nullable field inside an object array (where strictNullCheck is set to true), the compiler may still raise an error saying that 'Object is possibly undefined'. Here's an example: interface IA ...

Modifying the key values of an associative array

In my code snippet, I am attempting to loop through a JSON array and update the values within it. Here is an overview of what the JSON structure looks like: <?php $json='[{"type":"dropdown","label":"Is the property tenanted ?","req":0,"choices":[{ ...

Manage the appearance of a component using props

Here is the code snippet that I am working with: export type BreadcrumbItemProps = { isCurrent?: boolean; }; const isCurrent = (props: { isCurrent?: boolean }) => props.isCurrent ? 'normal' : 'bold'; export const Item = styled.s ...

What is the web address to access when removing an object from the system?

I have set up a local server to experiment with an API in Django. My model, 'Users', is filled with multiple objects and I am utilizing DefaultRouter. If I wanted to DELETE a specific object from this model, what would the URL look like? For ins ...

Generating JButtons on the fly along with attaching addActionListener and then parsing JSON to retrieve a

Trying to automate the population of actionListener for buttons, but encountering an error at jObject = jArray.getJSONObject(i) when the generator() function returns a JSONArray. Additionally, aiming to change buttons[i] = new JButton("pfdfs"); to buttons ...

Why is the data retrieved using ActivatedRoute.snapshot.data['']?

Recently delving into Angular, I stumbled upon this snippet of code: export class ProductListComponent implements OnInit { private Products: Product[]; constructor(private _activatedRoute: ActivatedRoute) { } ngOnInit() { this.Produc ...

Cross-origin resource sharing (CORS) is preventing access because the origin and allowed origin match

Utilizing Dockerized Ory Kratos and Angular (www folder hosted via nginx for header modifications) on localhost and attempting to run the following code: const headers = { Accept: 'application/json', }; fetch('http://127.0.0.1:4433/self-s ...

When running the command ng build --prod, it seems that the module for class X cannot be determined. To resolve this issue, make sure to include

I'm encountering an issue while trying to develop my Angular 5 application. The error message reads: Cannot determine the module for class ThreadListTabsComponent in /home/brightwater/Differ/src/app/thread-lists/thread-lists.component.ts! Add T ...

What is the best way to implement a loop through a JSON string in AngularJS?

I have a JSON string that looks like this : {"age":[459,918],"id":["bizno459","bizno459"],"name":["name459","wrongname459"]} Now I want to display it using AngularJS in the following format : <table> <tr> <th>column</th> ...

Error Message: Unexpected character "C" found in JSON response from Ionic 2 Http GET request

Trying to execute a GET request and extract data from the response. this.http.get('http://localhost:8888/maneappback/more-items.php').subscribe(res => { console.log(res.json()); }, (err) => { console.log(err); }); An error message ...

Outputting undefined values when processing an http post array

I seem to have encountered a major issue. Despite my efforts, I am seeing an undefined value when trying to display this JSON data. {"StatusCode":0,"StatusMessage":"OK","StatusDescription":{ "datas": [ {"sensor_serial":"SensorSerial1", "id":"11E807676E3F3 ...

Using Typescript to overload functions with varying first parameters

I am facing a scenario where I have a parent class that requires a method implementation with either one or two parameters depending on the child class. class MyClass { update(obj: HashMap); update(id: ID, obj: HashMap); update(objOrId: HashM ...

Changing a portion of a string into a java.util.Date

After posting DateTime as JSON, it gets transformed into "/Date(1512839439513)/" I am looking to simply convert this format to java.util.Date "/Date(1512839439513)/" needs to be converted to java.util.Date My attempt so far: String date = finalObject.g ...

What is the process for removing a document with the 'where' function in Angular Fire?

var doc = this.afs.collection('/documents', ref => ref.where('docID', '==', docID)); After successfully retrieving the document requested by the user with the code above, I am unsure of how to proceed with deleting that do ...