In your product.service.ts you are using stringify method in a wrong way..
Just use
JSON.stringify(product)
instead of
JSON.stringify({product})
i have checked your problem and after this it's working absolutely fine.
Answer from Akshay Rao on Stack OverflowIn your product.service.ts you are using stringify method in a wrong way..
Just use
JSON.stringify(product)
instead of
JSON.stringify({product})
i have checked your problem and after this it's working absolutely fine.
You'll have to parse again if you want it in actual JSON:
JSON.parse(JSON.stringify(object))
If you use a TypeScript interface instead of a class, things are simpler:
Copyexport interface Employee {
typeOfEmployee_id: number;
department_id: number;
permissions_id: number;
maxWorkHours: number;
employee_id: number;
firstname: string;
lastname: string;
username: string;
birthdate: Date;
lastUpdate: Date;
}
let jsonObj = JSON.parse(employeeString); // string to "any" object first
let employee = jsonObj as Employee;
If you want a class, however, simple casting won't work. For example:
Copyclass Foo {
name: string;
public pump() { }
}
let jsonObj = JSON.parse('{ "name":"hello" }');
let fObj = jsonObj as Foo;
fObj.pump(); // crash, method is undefined!
For a class, you'll have to write a constructor which accepts a JSON string/object and then iterate through the properties to assign each member manually, like this:
Copyclass Foo {
name: string;
constructor(jsonStr: string) {
let jsonObj = JSON.parse(jsonStr);
for (let prop in jsonObj) {
this[prop] = jsonObj[prop];
}
}
}
let fObj = new Foo(theJsonString);
The reason that the compiler lets you cast the object returned from JSON.parse to a class is because typescript is based on structural subtyping.
You don't really have an instance of an Employee, you have an object (as you see in the console) which has the same properties.
A simpler example:
Copyclass A {
constructor(public str: string, public num: number) {}
}
function logA(a: A) {
console.log(`A instance with str: "${ a.str }" and num: ${ a.num }`);
}
let a1 = { str: "string", num: 0, boo: true };
let a2 = new A("stirng", 0);
logA(a1); // no errors
logA(a2);
(code in playground)
There's no error because a1 satisfies type A because it has all of its properties, and the logA function can be called with no runtime errors even if what it receives isn't an instance of A as long as it has the same properties.
That works great when your classes are simple data objects and have no methods, but once you introduce methods then things tend to break:
Copyclass A {
constructor(public str: string, public num: number) { }
multiplyBy(x: number): number {
return this.num * x;
}
}
// this won't compile:
let a1 = { str: "string", num: 0, boo: true } as A; // Error: Type '{ str: string; num: number; boo: boolean; }' cannot be converted to type 'A'
// but this will:
let a2 = { str: "string", num: 0 } as A;
// and then you get a runtime error:
a2.multiplyBy(4); // Error: Uncaught TypeError: a2.multiplyBy is not a function
(code in playground)
Edit
This works just fine:
Copyconst employeeString = '{"department":"<anystring>","typeOfEmployee":"<anystring>","firstname":"<anystring>","lastname":"<anystring>","birthdate":"<anydate>","maxWorkHours":0,"username":"<anystring>","permissions":"<anystring>","lastUpdate":"<anydate>"}';
let employee1 = JSON.parse(employeeString);
console.log(employee1);
(code in playground)
If you're trying to use JSON.parse on your object when it's not a string:
Copylet e = {
"department": "<anystring>",
"typeOfEmployee": "<anystring>",
"firstname": "<anystring>",
"lastname": "<anystring>",
"birthdate": "<anydate>",
"maxWorkHours": 3,
"username": "<anystring>",
"permissions": "<anystring>",
"lastUpdate": "<anydate>"
}
let employee2 = JSON.parse(e);
Then you'll get the error because it's not a string, it's an object, and if you already have it in this form then there's no need to use JSON.parse.
But, as I wrote, if you're going with this way then you won't have an instance of the class, just an object that has the same properties as the class members.
If you want an instance then:
Copylet e = new Employee();
Object.assign(e, {
"department": "<anystring>",
"typeOfEmployee": "<anystring>",
"firstname": "<anystring>",
"lastname": "<anystring>",
"birthdate": "<anydate>",
"maxWorkHours": 3,
"username": "<anystring>",
"permissions": "<anystring>",
"lastUpdate": "<anydate>"
});
Convert JSON to object type in Angular - Stack Overflow
Convert JSON objects to JSOn array
How to convert string to object in Angularjs [duplicate]
Angularjs converting json data to "[object Object]"
Videos
you can use class-transformer which helps you to convert plain javascript objects to real es6 classes. With this real instances you can also use class methods.
import { Component, OnInit } from "@angular/core";
import ProductsJson from "./products.json";
import {plainToClass} from "class-transformer";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
productsJson: any = ProductsJson;
products: Array<Product>;
constructor() {}
ngOnInit() {
//this.products = <Product[]>this.productsJson;
this.products = plainToClass(Product, this.productsJson as []);
console.log(this.products);
}
}
export class Product {
id: number;
name: string;
description: string;
relatedProducts: Array<number>;
getId(){
return this.id + "_ID";
}
}
template:
<ul>
<li *ngFor="let p of products">
{{p.getId()}} {{p.id}} {{p.name}}
</li>
</ul>
look at stackblitz
Let me know still you have an issue..
thanks
You are passing the data as a parameter, hence you should not use $scope prefix. Instead just use data.
$scope.updateDetails = function (data) {
$scope.editedArrayDetails = [];
$scope.editedArrayDetails.push(data);
$scope.json = angular.toJson(data);
console.log($scope.json )
$scope.goEvent();
}
You need to print $scope.json not $scope.data, also it should not be $scope.data when you convert, it should be data
$scope.json = angular.toJson(data);
console.log($scope.json)
As Abdul has pointed out you have a JSON array and you want a JSON object, there you need
var eachProduct =
{
"name": name,
"id": id,
"category":category,
"price":price
};
Now alert(eachProduct.name); will return name. And I assume by "How to pass the function parameters to the each product" you mean add an attribute to your JSON object. To do this you you would have
eachProduct["someAttribute"]='"value":someValue';
You have declared eachProduct as an array, you need to use eachProduct[0].name instead.