instead of in your code:
...
this.searchResult = profileResponse;
...
you can use:
searchResult: any[];
...
this.searchResult = profileResponse.json() || {}
...
then you can access each property via searchResult item:
this.searchResult[0].profileId, etc
Answer from Joseph Wu on Stack Overflowinstead of in your code:
...
this.searchResult = profileResponse;
...
you can use:
searchResult: any[];
...
this.searchResult = profileResponse.json() || {}
...
then you can access each property via searchResult item:
this.searchResult[0].profileId, etc
Update based on comment code:
The reason you're not able to access the properties of searchResult is that the service is returning a response rather than a Javascript object with properties.
From the HTTP Angular docs here:
The response data are in JSON string form. The app must parse that string into JavaScript objects by calling response.json().
I suggest parsing the response in the service to keep things related to the http request there and prevent code duplication.
Change:
return this.http.post(this._url, body, options).map((response: Response) => {
return response;
}).catch((error) => {
return Observable.throw(error);
});
To this (if indeed you only want the first profile in the array):
return this.http.post(this._url, body, options).map((response: Response) => {
return response.json()[0];
}).catch((error) => {
return Observable.throw(error);
});
The new code parses the JSON object and extracts the first object from the array with .json()[0]. Then rename profileResponse to profileDetails and access this.searchResult's properties using dot notation:
e.g. From another function in the component:
console.log(this.searchResult.profileName)
e.g. From your template:
{{searchResult.profileName}}
Parsing Json Array in AngularJS - Stack Overflow
Convert JSON file to Typescript Array of Objects
The interface has an iD field and the json has a date field. They need to be the same types. You also might need to use JSON.parse(stringValue) depending on how you are getting the JSON data.
More on reddit.comtypescript - How to parse the Json array from Json object using angular - Stack Overflow
Parse JSON file with arrays using AngularJS - Stack Overflow
Videos
In your controller you should assign your json to a scope:
app.controller('myctrl', function($scope, $http) {
$scope.myArray = [];
$http.get("http://localhost:8080/xyz").then(function (response) {
$scope.myArray = response;
});
});
Then in your view, you can do something like:
<div ng-controller="myctrl">
<ul ng-repeat="obj in myArray">
<li>{{obj.city}}</li>
</ul>
</div>
use ng-repeat like this.
<div ng-repeat="t in test">
<span>{{t.city}}</span>
</div>
plunker here
I am reading in a JSON file and attempting to convert them to an array of objects. I get a syntax error on the component file.
This is the component code:
import * as blogs from '../story/stories.json';
import { IStory } from '../models/story';
@Component({
selector: 'app-story',
templateUrl: './story.component.html',
styleUrls: ['./story.component.scss']
})
export class StoryComponent implements OnInit {
stories: IStory[] ;
constructor() { }
ngOnInit() {
this.stories = blogs; <-- syntax error on this line
}this is the story.ts file:
export interface IStory {
id: number;
author: string;
title: string;
pictureUrl: string;
body: string;
}This is the json file, stories.json
[
{"date":3,"author":"AVC", "pictureUrl":"Scorching", "title":"Scorching", "body":"Scorching"},
{"date":4,"author":"ADF", "pictureUrl":"Scorching", "title":"Scorching", "body":"Scorching"}
]The interface has an iD field and the json has a date field. They need to be the same types. You also might need to use JSON.parse(stringValue) depending on how you are getting the JSON data.
It might be simpler to just use the http client to get the json. Pass it the type and you should get proper data objects back.
You can't iterate over your JSON since it represented not as array but Object.
Set braces like:
[
{
"1590": {
"id": "1590",
"id_site": "0",
"id_merk": "7",
"id_type": "209",
"uitvoering": "Blue Lease Execut. HYbrid4 2.0 HDi 4D 147kW"
}
},
{
"1590": {
"id": "1590",
"id_site": "0",
"id_merk": "7",
"id_type": "209",
"uitvoering": "Blue Lease Execut. HYbrid4 2.0 HDi 4D 147kW"
}
}
]
The second option is key-value presentation:
{
"1590": {
"id": "1590",
"id_site": "0",
"id_merk": "7",
"id_type": "209",
"uitvoering": "Blue Lease Execut. HYbrid4 2.0 HDi 4D 147kW"
},
"1591": {
"id": "1591",
"id_site": "0",
"id_merk": "7",
"id_type": "201",
"uitvoering": "Blue Lease Execut. HYbrid4 2.0 HDi 4D 142kW"
}
}
So HTML should be like:
<select data-ng-model="selectedItem"
data-ng-options="key as value.uitvoering for (key , value) in brands">
<option value="">-- Selecteer een merk --</option>
</select>
See Demo in Fiddle
Helper You can use this online helper: jsoneditoronline
I write an example for you: plnkr
First, the json you provided is not a valid json. Based on the structure you may have to change the expression in ng-options. And then, I recommend you return the $http promise to controller and parse the result after doing ajax. Finally, you render the result to the select element. I hope this will help you. You can also see the api doc ng on select if you want more detail of select options.
I think it's because of your mapping in your product class and also the type of your class, try to change class Product to interface Product
like this
export interface Product{
public id: number;
public name: string;
public category: string;
public price: number;
public description: string;
public currencyCode: string;
}
you can go take a look at Angular : Class and Interface for the differences between class and interface
EDIT : (as you can see in my code, I also changed the variable name to match with your JSON response)
Another approach could be to make JSON data, compatible with your Product class. You could use the map rxjs operator to transform your JSON data into Product. Modify the get products code, like this
const source$ = of(result).pipe(pluck('result'),map(item=> item.map(x=>{
let product = new Product(x.id,x.name, x.category, x.price, x.description, x.currencyCode);
return product;
})));
Here is a StackBlitz link.
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>"
});
Try like this
View
<div ng-controller="MyCtrl">
<div ng-repeat="user in _users" ng-init="myInfo=parJson(user.User.lastlogin)">
<div ng-repeat="emp in myInfo.employees">{{emp.firstName}}</div>
</div>
</div>
Controller
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.getName = function (user) {
return "Names";
};
$scope._users = [{
"User": {
"userid": "dummy",
"lastlogin": "{\"employees\":[{\"firstName\":\"John\"}, {\"firstName\":\"Blake\"}]}",
}
}];
$scope.parJson = function (json) {
return JSON.parse(json);
}
//console.log(JSON.parse($scope._users[0].User.lastlogin));
}
DEMO
you can also use angular.fromJson.
Like this
$scope.parJson = function (json) {
return angular.fromJson(json);
}
DEMO
To parse "lastlogin": "{\"employees\":[{\"firstName\":\"John\"}, {\"firstName\":\"Blake\"}]}" data correctly you can use
angular.fromJson(User.lastLogin);
Just make sure that you are giving inner object i.e. lastlogin to the method and it will remove all invalid characters such as \ and " from the json data.
