Converting Angular 2/TypeScript classes into JSON format

I am currently working on creating a class that will enable sending a JSON object to a REST API. The JSON object that needs to be sent is as follows:

{
  "libraryName": "temp",
  "triggerName": "trigger",
  "currentVersion": "1.3",
  "createdUser": "xyz",
  "visibilityType": "private",
  "WFAllowdTeam": {
    "allowedTeam": "team1"
  },
  "WFLibraryHistory": {
    "createdDate": "2016-7-7T05:10:04.106Z",
    "modifiedDate": "2016-7-9T05:10:04.106Z"
  }
}

I attempted to create a class and set the data by initializing the object like

this.library.WFAllowdTeam.WFAllowdTeam = 'team';
. You can see the class I created below:

   class WFLibraryHistory {
        public createdDate: any;
        public modifiedDate: any;
    }

    class WFAllowdTeam {
        public WFAllowdTeam: string;
    }

    export class Library {
        public libraryName: string;
        public triggerName: string;
        public currentVersion: string;
        public createdUser: string;
        public visibilityType: string;
        public libraryID: string;
        WFLibraryHistory: WFLibraryHistory;
        WFAllowdTeam: WFAllowdTeam;
    }

The error message encountered is as follows:

platform-browser.umd.js:937 TypeError: Cannot set property 'WFAllowdTeam' of undefined
    at WFLibraryComponentAddNewWorkflow.createWorkflow (wf-library.component.new.workflow.ts:47)
    at DebugAppView._View_WFLibraryComponentAddNewWorkflow0._handle_click_61_0 (WFLibraryComponentAddNewWorkflow.ngfactory.js:488)
    at eval (core.umd.js:12718)
    at SafeSubscriber.schedulerFn [as _next] (core.umd.js:9181)
    at SafeSubscriber.__tryOrUnsub (Subscriber.ts:240)
    at SafeSubscriber.next (Subscriber.ts:192)
    at Subscriber._next (Subscriber.ts:133)
    at Subscriber.next (Subscriber.ts:93)
    at EventEmitter.Subject._finalNext (Subject.ts:154)
    at EventEmitter.Subject._next (Subject.ts:144)

Any guidance or assistance in resolving this issue would be greatly appreciated.

Answer №1

Make sure to initialize all the members of the class first.

export class Library {
    public libraryName: string;
    public triggerName: string;
    public currentVersion: string;
    public createdUser: string;
    public visibilityType: string;
    public libraryID: string;
    WFLibraryHistory: WFLibraryHistory;
    WFAllowdTeam: WFAllowdTeam;

    constructor() {
       this.WFLibraryHistory = new WFLibraryHistory();
       this.WFAllowdTeam = new WFAllowdTeam();
    }
}

Answer №2

In order to make changes to the attributes of WFAllowdTeam, you must first create a new instance of it.

Create a new instance of WFAllowdTeam by using: 
this.library.WFAllowdTeam = new WFAllowdTeam();
Then, assign a value to the WFAllowdTeam attribute like this:
this.library.WFAllowdTeam.WFAllowdTeam = 'team';

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

The callback function is no longer accepted by the Model.prototype.save() method

Even after exploring various questions and answers on StackOverflow, I am still facing a persistent issue. The problem revolves around an app designed for inputting items and pushing them to a MongoDB database. However, I keep encountering errors. I am in ...

Parsing JSON data in Oracle database allows you to extract specific values from

I am looking to retrieve the values of marketDescription and channelName attributes as separate columns from the JSON data provided below: { 'betType':'SYSTEM', 'multiplier':1, 'selections':[ { ' ...

Passing a JSON object to a different page using jQuery

I'm currently facing a challenge with sending JSON data (demographics) to a new page within the same directory when a user clicks on a marker that I've placed on a Google map on my website. I am using the jquery-ui-map plugin, and while the marke ...

ngx-graphs -> ngx-graphs-bar-vertical x-axis labels with multiple lines

I'm using 'ngx-charts' with Angular, and I have encountered an issue with long text on my X axis labels. The text overflows and displays three dots instead of wrapping onto multiple lines. Is there a way to make the text wrap onto multiple l ...

How to use multiple template urls in Angular 6

Currently, I am creating a front-end using Angular 6 and facing the challenge of having components with varying html structures based on the user who is logged in. The number of templates required can range from 2 to over 20, so my preference would be to ...

Download Android contact information in csv layout

Hello, I am new to Android and interested in learning how to export my contacts into a CSV format. I need to transfer the file to a web server and store it in a centralized database using MySQL. Using vCard is not my preferred method... Alternatively ...

Indicate a specific type for the Express response

Is there a method to define a specific type for the request object in Express? I was hoping to customize the request object with my own type. One approach I considered was extending the router type to achieve this. Alternatively, is there a way to refactor ...

The parameter type '{ src: string; thumb: string; }' cannot be assigned to the 'never' type in the argument

Sample Typescript Code: I am experiencing issues with my code and cannot comprehend this error message- Argument of type '{ src: string; thumb: string; }' is not assignable to parameter of type 'never' _albums = []; constructor( ...

Could anyone provide an explanation for the statement "What does '[P in keyof O]: O[P];' signify?"

As a new Typescript user looking to build a passport strategy, I came across a line of code that has me completely baffled. The snippet is as follows: here. The type StrategyCreated<T, O = T & StrategyCreatedStatic> = { [P in keyof O]: O[P]; ...

transforming object into a string in Java while eliminating superfluous characters

While working with a Java object, I encountered an issue when converting it to a JSON string format. The code snippet causing the problem is: new JSONObject(responseDTO.getDTOHeader()).toString(); The resulting string contains unexpected characters, such ...

Ways to initiate a web request prior to parsing JSON data

I've been struggling to make a web request before trying to deserialize my url. So far, none of the usual methods for making web requests seem to be working. public WeatherModel GetWeather(string url) { WeatherModel WeatherData = new ...

Retrieve the value of a child variable within a parent button's action event

Is there a way to access the value of a child variable from a parent button click? child component @Component({ selector: 'app-child-panel', templateUrl: './child-panel.component.html', styleUrls: ['./child-panel.component.sc ...

The challenge with the Optional Chaining operator in Typescript 3.7@beta

When attempting to utilize the Typescript optional chaining operator, I encountered the following exception: index.ts:6:1 - error TS2779: The left-hand side of an assignment expression may not be an optional property access. Here is my sample code: const ...

Applying styles to every tr element in Angular 2 components

I'm trying to use background-color with [ngClass] on a table row. The styles are being applied, but they're affecting all rows' backgrounds. I want the background color to only change for the specific row that is clicked. Here is my code: ...

Tips for troubleshooting an Angular error when no specific information is provided

I'm encountering an error `ERROR Error: "[object Object]" in my console and my app is displaying a white screen. Everything was working perfectly fine before, and I can't pinpoint any changes that may have caused this issue. The error appears to ...

Is there a way to access every item that includes a particular attribute and attribute term within the woocommerce-rest-api?

Struggling to retrieve products that have the "x-attribute" and "x-attribute-term" using Node.js with the WooCommerce REST API library from here. I've explored solutions on stackoverflow and other sites but none seem to work. Atte ...

Show a reset button in an Angular 2 reactive form only when the form has unsaved changes

I am working with a reactive form and need to add a reset button that will return the form values to their initial state. The reset button should only be visible if the form is dirty. Here is the form definition: this.form = new FormGroup({ firstName: ...

Deleting the First Item from an Array in Typescript using Angular

Clicking my Button in .html <button (click)="deleteFirst()">Delete First</button> My array setup and removal function in .ts: people = [ {first: "Tom", last: "Brown"}, {first: "Ben", last: &qu ...

What are the steps for incorporating the AAD B2C functionality into an Angular2 application with TypeScript?

I recently built a web application using Angular2 and TypeScript, but now one of my clients wants to integrate Azure B2C for customer login instead of OAuth. I followed a simple example on how to implement Azure B2C in a .NET Web app through the link provi ...

How to use Handlebars in Node.js to parse JSON data

When using Form API in node.js, I encountered JSON data that needs to be parsed. As a beginner, I am unsure how to handle this JSON data properly. [ { "Detail": " Rs. 1001 Full Talktime Topup Rs.1001 Full Talktime", "Amount": "1001", "Validity" ...