When I try to display my subData in Angular I get [object Object]:
enter image description here
I have a model that can contain an array of sites:
public class Site
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Url { get; set; } = string.Empty;
public Site[]? SubData { get; set; }
}
JSON Example:
{
"id": 1,
"name": "Google",
"url": "http://www.google.com",
"subData": [
{
"id": 2,
"name": "Walla",
"url": "http://www.walla.co.il"
}
]
},
components.ts:
export class AppComponent implements OnInit{
sites: Site[] = [];
constructor(private siteService:SiteService) { }
ngOnInit(): void {
this.GetSites();
}
GetSites() {
this.siteService.GetSites()
.subscribe((sites) => {
JSON.stringify(this.sites = sites);
});
}
}
html:
<div *ngFor="let item of sites;">
<div>Id: {{item.id}}</div>
<div>Site Name: {{item.name}}</div>
<div>Site Url: {{item.url}}</div>
<div>{{item.subData}}</div>
</div>
You make it even cleaner with async pipe:
<div *ngFor="let item of sites$ | async as site;"> // use async pipe here
<div>Id: {{site.id}}</div>
<div>Site Name: {{site.name}}</div>
<div>Site Url: {{site.url}}</div>
// use ngfor for subdata
<div *ngFor="let subSite of site?.subData"> // use ? for safety
<div> {{subSite?.url}}</div>
</div>
</div>
export class AppComponent implements OnInit{
sites$: Observable<Site[]>;
constructor(private siteService:SiteService) { }
ngOnInit(): void {
this.GetSites();
}
GetSites() {
this.sites$ = this.siteService.GetSites();
}
}
use json pipe something like
<div>{{item.subData | json}}</div>
Update as per comment to display as html element use ngFor loop
<div *ngFor="let i of item.subData">
<div> {{i.url}}</div>
</div>
Related
JSON File:
{
"Students": [
{
"id": 1,
"name": "Ravi",
"department": "IT"
},
{
"id": 2,
"name": "Raj",
"department": "hr"
},
{
"id": 3,
"name": "avi",
"department": "it"
}
]}
ASP.NET MVC model classes:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
}
public class Root
{
public List<Student> Students { get; set; }
}
ASP.NET MVC controller for receiving data from a jQuery POST request, and sending that data to the API:
public class StudentController : Controller
{
HttpClientHandler _clientHandler = new HttpClientHandler();
[HttpPost]
public async Task<List<Student>> AddUser(Student _Students)
{
OStudents = new List<Student>();
using (var httpclient = new HttpClient(_clientHandler))
{
StringContent content = new StringContent(JsonConvert.SerializeObject(_Students), Encoding.UTF8, "application/json");
using (var response = await httpclient.PostAsync("https://localhost:7018/api/Students/AddUser", content))
{
string res = await response.Content.ReadAsStringAsync();
OStudents = JsonConvert.DeserializeObject<List<Student>>(res);
}
}
return OStudents;
}
}
jQuery code: for sending data to AddUser function:
function AddStudent() {
oStudent = {
id: $("#st-Id").val(),
name: $("#st-Name").val(),
department: $("#st-Department").val()
};
$.post("/Student/AddUser", oStudent);
$.ajax({
url: "/Student/AddUser",
type: 'POST',
data: oStudent,
contentType: 'application/json',
dataType: 'json',
success: function (msg) {
alert(msg);
}
});
Web API files:
Classes:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
}
public class Students
{
public List<Student> students { get; set; }
}
ApiController for adding data received from ASP.NET MVC application to JSON file
[HttpPost("AddUser")]
public IActionResult AddUser(Students _Student)
{
var filePath = #"C:/Users/tanmay_pawar/source/repos/CRUDAPI/CRUDAPI/output.json";
var json = System.IO.File.ReadAllText(filePath);
Students students = JsonConvert.DeserializeObject<Students>(json);
students.students.AddRange(_Student.students);
json = JsonConvert.SerializeObject(students);
System.IO.File.WriteAllText(filePath, json);
return Ok();
}
My POST method in the Web API is receiving null values.
oStudent is not a JSON object. It is a normal JavaScript object.
If you want to send the data as JSON, you have to encode it first:
data: {_Student: JSON.stringify(oStudent)}
You can receive this data with a string type parameter on the server side and then deserialize the object.
[HttpPost("AddUser")]
public IActionResult AddUser(string _Student)
{
List<Student> students = JsonConvert.DeserializeObject<List<Student>>(_Student);
return Ok();
}
I get my values from the api that look like this. I am trying to get the values inside the mapping array of objects
{
"aMovieId": 1,
"aTitle": "Django Unchained",
"aRating": 4,
"aImageLink": "http://upload.wikimedia.org/wikipedia/en/8/8b/Django_Unchained_Poster.jpg",
"aTrailerLink": "//www.youtube.com/embed/eUdM9vrCbow",
"aGenre": "Western",
"aWideImage": "images/django.jpg",
"tblMovieActorMapping": [
{
"aActor": {
"aActorName": "Leonardo Di Caprio"
}
},
{
"aActor": {
"aActorName": "Christoph Waltz"
}
}
],
"tblMovieDirectorMapping": [
{
"aDirector": {
"aDirectorName": "Martin Scorsese"
}
},
{
"aDirector": {
"aDirectorName": "Sofia Coppola"
}
}
]
}
and I am trying to display the values in HTML like this-
<p >
<img alt={{movie.aTitle}} src="../{{movie.aWideImage}}" /><br>
{{movie.aMovieId}}<br>
{{movie.aTitle}}<br>
{{movie.aMovieDescription}}<br>
{{movie.aDuration}}<br>
{{movie.aGenre}}<br>
{{movie.tblMovieActorMapping}}
{{movie.tblMovieDirectorMapping}}
<img width=200px height=300px alt={{movie.aTitle}} src={{movie.aImageLink}} /><br>
<iframe width=560px height=315px src={{movie.aTrailerLink}} frameborder="0" allowfullscreen></iframe>
How do i access the values inside the mapping?
Also I am not able to interpolate inside the iframe tag.
Here is a working demo like below:
fetch-data.component.html:
<table class='table table-striped' aria-labelledby="tableLabel" >
<tbody>
<tr>
<td><img width="100" height="100" alt={{movie.aTitle}} src="../{{movie.aWideImage}}" /></td>
<td>{{movie.aMovieId}}</td>
<td>{{movie.aTitle}}</td>
<td>{{movie.aMovieDescription}}</td>
<td>{{movie.aDuration}}</td>
<td>{{movie.aGenre}}</td>
<td>
<table>
<tr *ngFor="let index of movie.tblMovieActorMapping; index as i">
<td>{{movie.tblMovieActorMapping[i].aActor.aActorName}}</td>
</tr>
</table>
</td>
<td>
<table>
<tr *ngFor="let index of movie.tblMovieDirectorMapping; index as i">
<td>{{movie.tblMovieDirectorMapping[i].aDirector.aDirectorName}}</td>
</tr>
</table>
</td>
<td><img width="200" height="300" alt={{movie.aTitle}} src={{movie.aImageLink}} /></td>
<td>
<iframe width="450" height="300" [src]='safeUrl' frameborder="0" allowfullscreen></iframe>
</td>
</tr>
</tbody>
fetch-data.component.ts:
import { Component, OnInit} from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { DomSanitizer } from '#angular/platform-browser';
#Component({
selector: 'app-fetch-data',
templateUrl: './fetch-data.component.html'
})
export class FetchDataComponent implements OnInit {
movie: any = [];
safeUrl: any;
constructor(private sanitizer: DomSanitizer,private http: HttpClient) { }
ngOnInit() {
this.http.get('https://localhost:44366/weatherforecast')
.subscribe(
(data) => {
console.log(data);
this.movie = data;
this.safeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.movie.aTrailerLink);
});
}
}
My testing controller:
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpGet]
public Test Get()
{
var data = System.IO.File.ReadAllText("test1.json");
var model = JsonSerializer.Deserialize<Test>(data);
return model;
}
}
My testing model:
public class Test
{
public int aMovieId { get; set; }
public string aTitle { get; set; }
public int aRating { get; set; }
public string aImageLink { get; set; }
public string aTrailerLink { get; set; }
public string aGenre { get; set; }
public string aWideImage { get; set; }
public Tblmovieactormapping[] tblMovieActorMapping { get; set; }
public Tblmoviedirectormapping[] tblMovieDirectorMapping { get; set; }
}
public class Tblmovieactormapping
{
public Aactor aActor { get; set; }
}
public class Aactor
{
public string aActorName { get; set; }
}
public class Tblmoviedirectormapping
{
public Adirector aDirector { get; set; }
}
public class Adirector
{
public string aDirectorName { get; set; }
}
Result:
Able to receive response from server as a JSON object.Tried to cast JSON object to emp (type Employee),but not happening. What is the problem with my code?? Is there another way to solve this??
app.component.ts
export class AppComponent implements OnInit{
title = 'httpClientProject';
posts : JsonGet[];
emp : Employee;
constructor(private appService : AppService,private employeeService : EmployeeService){}
ngOnInit(){
this.getData();
this.getEmployee();
console.log(this.emp) }
getData() : void{
this.appService.getData().subscribe(posts=>(this.posts = posts)); }
getEmployee() : void{
this.employeeService.getEmployee().subscribe(data=>this.emp={...data}); } }
employee.service.ts
export class EmployeeService {
private baseUrl = 'http://localhost:8080/SpringRestWebService/getSingleEmployye';
constructor(private http: HttpClient) { }
getEmployee(): Observable<Employee> {
return this.http.get<Employee>(this.baseUrl); } }
Employee.ts
export class Employee {
public id: number;
public name: string;
public city: string;
constructor(id:number, name:string, status:string) {
this.id = id;
this.name = name;
this.city = status; } }
Json Response From Server
{
"id": 1,
"name": "asdasd",
"city": "Hasdasdayd"
}
Just define type when passing variable in subscribe
getEmployee() : void{
this.employeeService.getEmployee().subscribe((data:Employee)=>{
this.emp=data;
}
}
I'm having problems deserializing a .NET List into an Angular 2 array. I keep receiving an error:
ERROR Error: Cannot find a differ supporting object...NgFor only supports binding to Iterables such as Arrays.
I've checked here but none of the proposed solutions have been working for me: https://github.com/angular/angular/issues/6392
C#
Model
public class Filter
{
public string filterType { get; set; }
public string filterKey { get; set; }
public string filterValue { get; set; }
}
Controller Action
public List<Filter> Filters { get; set; } = new List<Filter>()
{
new Filter()
{
filterType = "TypeA",
filterValue = "ValueA",
filterKey = "TypeA|ValueA"
},
new Filter()
{
filterType = "TypeB",
filterValue = "ValueB",
filterKey = "TypeB|ValueB"
}
};
// GET api/values
[HttpGet]
public ActionResult Get()
{
var response = JsonConvert.SerializeObject(Filters);
return new JsonResult(response);
}
I have confirmed with both POSTMAN and Chrome Developer Tool's that this controller is correctly returning the JSON:
[{"filterType":"TypeA","filterValue":"TypeA","filterKey":"TypeA|ValueA"},
{"filterType":"TypeB","filterValue":"ValueB","filterKey":"TypeB|ValueB"}]
Angular
Model (filter.ts)
export class Filter{
filterType: string;
filterKey: string;
filterValue:string;
}
Service (filter.service.ts)
#Injectable()
export class FilterService {
private apiUrl: string = "http://localhost:7639/api/filters";
constructor(private http: Http) { }
public getFilters = (): Observable<Filter[]> => {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.get(this.apiUrl,options)
.map(res => <Filter[]>res.json())
.do(x => console.log(x)) <-- This clearly logs the JSON
.catch(this.handleError);
}
private handleError(error:Response){
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
Component (filter.component.ts)
export class FilterComponent implements OnInit{
title = 'Filters';
public filters: Filter[];
constructor(private filterService: FilterService) {
}
ngOnInit() {
this.getFilters();
}
private getFilters(){
this.filterService.getFilters().subscribe(filters => {
this.filters = filters;
console.log(filters);
},
error => {
console.log(error);
}, () => {
});
}
}
Component HTML (filter.component.html)
<h1>{{title}}</h1>
<div *ngFor="let filter of filters">
<p>{{filter.filterType}}</p>
<p>{{filter.filterValue}}</p>
<p>{{filter.filterKey}}</p>
</div>
Any help with this would be appreciated
The answer was super simple.
// GET api/values
[HttpGet]
public ActionResult Get()
{
var response = JsonConvert.SerializeObject(Filters);
return new JsonResult(response);
}
I was doing redundant serialization on the list and passing the response back as a string.
Changing the above method corrected the issue:
// GET api/values
[HttpGet]
public ActionResult Get() => new JsonResult(Filters);
Can anyone lead me to examples showing how to convert incoming JSON to a Model in MVC3?
That's already handled for you by the framework.
So you define models:
public class MyViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public Complex Complex { get; set; }
public IEnumerable<Foo> Foos { get; set; }
}
public class Complex
{
public int Id { get; set; }
}
public class Foo
{
public string Bar { get; set; }
}
then a controller action taking this model:
[HttpPost]
public ActionResult SomeAction(MyViewModel model)
{
...
}
and finally you hammer this controller action with a JSON request matching the structure of your view model:
$.ajax({
url: '#Url.Action("SomeAction")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
id: 1,
name: 'john smith of course, why asking?',
complex: {
id: 3
},
foos: [
{ bar: 'the bar' },
{ bar: 'the baz' },
]
}),
success: function(result) {
alert('hooray');
}
});
http://james.newtonking.com/projects/json-net.aspx
I would add more, but the example code is also on that front page.