How to solve Angular [object object] in template - json

I am getting [object object] showing in my html page.
I am calling the a web service and in my console.log. I can see the full response but on my template I only see [object object]
test() {
this.http.post('api...', JSON.stringify(this.getAllCaseInfoWithCAS)).subscribe(data => {
this.testData = [data];
});
}
I have a ngFor
<ng-template ngbPanelContent>
<div class="row" *ngFor="let item of testData">
{{item.getAllCaseInfoWithCASReturn.caseDetails}}
</div>
</ng-template>
The response looks like this
{
"getAllCaseInfoWithCASReturn": {
"caseDetails": {
"caseNumber": "12345",
"componentDetails": {
"component": "29"
},
"personNumber": "5",
"month": "7"
}
}
}
How can I display all the information on the template?

You can use JsonPipe
{{ value_expression | json }}
Converts a value into its JSON-format representation. Useful for debugging.
{{ item.getAllCaseInfoWithCASReturn.caseDetails | json }}

Better start by making JSON formatted as an array of caseDetails, here is a rough code of what you can do with current JSON:
// This should be refactored to a service file.
getCaseDetails(data: any): Observable<any[]> {
const url = `api/url`;
return this.httpClient.post(url, data)
.pipe(
map(result => result['getAllCaseInfoWithCASReturn']['caseDetails']),
tap(caseDetail => console.log(caseDetail))
)
}
test() {
this.getCaseDetails(dummyData).subscribe(caseDetail => {
this.testData = caseDetail;
})
}
<ng-template ngbPanelContent>
<div class="row">
{{testData?.caseNumber}} <!-- or json pipe -->
{{testData?.personNumber}}
{{testData?.month}}
{{testData?.componentDetails?.component}}
</div>
</ng-template>

Related

Json data not showing in vuejs

I am making a vue app. I put a .json file in static directory. I am trying to read it in the default HelloWorld.vue file. But it's not showing in the browser. Here is what it shows in the browser:
My json file looks like this:
{
"status": "success",
"message": "Successfully retrieved all registered applications",
"Applications": [
{
"ApplicationID": "74382DOD",
"ApplicationName": "OIMInstance2",
"ApplicationType": "OIM",
"APIToken": "ZM8R4FRiZWWKbl235u06zbArCdOBPlEKhqHQO8Y9RJ2HgBPC+cZgbIli8fFuNZaey/2tJciJuILIWIn24WTjGA=="
},
{
"ApplicationID": "943ODA6G",
"ApplicationName": "LDAPInstance2",
"ApplicationType": "LDAP",
"APIToken": "R9lDEW5dnN6TZg2sefEEzS6LWMNmFh4iLHMu47LmAsusHl0bZuh2rktSlXqSZRdHHEWq7sP4Xsdy6xNtDYE8xw=="
}
]
}
My code in HelloWorld.vue is:
<template>
<div>
<h1>APPLICATION REGISTRATION</h1>
<div v-for="udata in userData">
Id : {{ udata.ApplicationID }}
</div>
</div>
</template>
<script>
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
export default {
name: 'HelloWorld',
data () {
return {
userData: []
}
},
created: function() {
axios.get('../../static/mockdata.json')
.then(response => {
this.userData = response.data
})
.catch(e => {
//this.errors.push(e)
})
}
}
</script>
Is there anything wrong with my code? How do I show the json data in the browser?
You need to iterate through applications object.Hence in order to get applicationId you will need to set data accordingly by only adding applications data in your userData variable.
Do as below.
this.userData = response.data.Applications

Formgroup binding in select boxes with Angular

I have a nested JSON array which i have to iterate to HTML using formgroup or formarray. This response is to be iterated into dynamically created select boxes depending on the length of array.
The JSON response coming in is:
var result = [{
id: 1,
options: [
{ option: 'Ram', toBeSelected: false },
{ option: 'Ravi', toBeSelected: true }
]
},
{
id: 2,
options: [
{ option: 'Pooja', toBeSelected: false },
{ option: 'Prakash', toBeSelected: false }
]
}
]
I have to iterate this into HTML in such a way that if any of these options have toBeSelected as true, that option should be preselected in HTML and if not, placeholder text can be shown.
According to the JSON in question, you can make it like:
ngOnInit() {
this.form = this._FormBuilder.group({
selections: this._FormBuilder.array([])
});
// the api call should be made here
this.jsonResponse.map(item => {
const opts = item.options.filter(o => {
return o.toBeSelected
});
if (opts.length) {
this.addSelections(opts[0].option);
} else {
this.addSelections();
}
});
}
get selections() {
return this.form.get('selections') as FormArray
}
addSelections(value?: string) {
this.selections.push(
this._FormBuilder.control((value ? value : ''))
);
}
Live view here.
Stackblitz link: https://stackblitz.com/edit/dynamic-form-binding-kx7nqf
Something along the lines of this?
<div *ngFor="let result of results">
<p>ID - {{ result.id }}</p>
<div *ngFor="let option of result.options">
<input
type="checkbox"
[checked]="option.toBeSelected">
{{ option.option }}
</div>
</div>
This isn't an example of FormGroup though but should help you understand how it can be done.
Sample StackBlitz

angular 2 cannot access array of objects from json

I am connecting my app with an API. whenever I do a post request, I will get a json back that looks like this
{
"output": {
"text": {
"values": [
"Sure ! What kind of mouse would you like"
],
"selection_policy": "sequential"
},
"cards": [
{
"Mouse_Type": "Wireless"
},
{
"Mouse_Type": "Optical"
}
]
}
}
in my html I have created this:
<ul class="cards-options">
<li *ngFor="let options of listOptions" >
<span class="card">
<p>{{options.Mouse_Type }}</p>
</span>
</li>
</ul>
my component is like this:
export class InputFieldComponent implements OnInit {
value = '';
listOptions = '';
public context :object;
constructor(private http : Http) { }
ngOnInit() {
}
onEnter(value: string) {
this.http.post('/APIconversation', {"input":value })
.map(response=>response.json())
.subscribe(
data => {
this.listOptions = data.output.cards;
console.log(this.listOptions);
}
)
}
Whenever I inspect the element of the *ngFor I find this:
bindings={ "ng-reflect-ng-for-of": "[object Object],[object
Object" }
How can I access the string within the object? I did the same exact thing with another API and it was working.
Thanks for your help.

How I get $key when I using ngFor using angularfire2?

I have some question, example I have a json file:
{
"items" : {
"khanh" : {
"name":"2017 shirt",
"size":["S","M","L"],
"image":"http://placehold.it/650x450",
"likes":0,
"price":123
},
"-KdleehAQm0HgVFYdkUo" : {
"name":"2017 shirt",
"size":["S","M","L"],
"image":"http://placehold.it/650x450",
"likes":0,
"price":123
},
"-Kdlg3AqKNTnbhjAVT8h" : {
"name":"2017 shirt",
"size":["S","M","L"],
"image":"http://placehold.it/650x450",
"likes":0,
"price":123
}
}
}
I have a button that update how many likes. But I have a problem. I don't know how to get the "key". Example:"khanh","-KdleehAQm0HgVFYdkUo"
This worked for me.
Component:
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
dbcomplextest: FirebaseListObservable<any[]>;
constructor(afDB: AngularFireDatabase) {
this.dbcomplextest = afDB.list('/complex/');
}
View:
<span *ngFor="let value of dbcomplextest | async">
{{ value.$key }} - {{ value.$value }}
</span>
In the latest version >=4.6.0, you have to use snapshotChanges().map() to store the key.
this.itemsRef = db.list('messages');
// Use snapshotChanges().map() to store the key
this.items = this.itemsRef.snapshotChanges().map(changes => {
return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
});
Then now you can be able to get it from your view list using .key

fail reading object type of json

i have an Object type of json that I cant read...
this is my json:
body: {
"111": {
"name": "name1",
"status": 10000
},
"222": {
"name": "name2",
"status": 20000
},
"333": {
"name": "name3",
"status": 30000
}
}
and I want to know how to present it in my html?
this is my attempt:
<md-content>
<h1 align="center">{{title}}</h1>
<h2>list of items:</h2>
<div class="list-bg" *ngFor="#item of items | async">
ID: {{item.name}} <p></p> Number of Items: {{item.status}}
</div>
</md-content>
not only that it dosent work, im trying to figure out how to read each line the object id's(those: 111, 222, 333)
this is my model:
export interface MyModel {
name: string;
status: number;
}
this is my component:
export class MyCmp implements OnInit {
retJson: Observable<MyModel[]>
constructor(private _myService: MyService) {};
public showData(): void {
this.retJson = this._myService.getData();
}
}
thanks!
You haven't included how you load your json, so I'll write a more general example:
interface MyModel {
name: string;
status: number;
}
interface MyResponse {
body: { [id: string]: MyModel }
}
let response: MyResponse = JSON.parse(RESPONSE_STRING);
Object.keys(response.body).forEach(id => {
let model = response.body[id];
console.log(`id: ${ id }, name: ${ model.name }, status: ${ model.status }`);
});
What's missing here is the RESPONSE_STRING, which I'm not sure how you get.
As for the template, I'm not an angular developer but as far as I understand ngFor is used for arrays, and you don't have an array in your json structure.
ngFor loop only will work for array. Your body json is key value object, so it wouldn't work.
If you want to make it work, it's either:
you use an additional pipe to convert key value object to array using pipe, solution discussed here: Iterate over TypeScript Dictionary in Angular 2, then you can use
*ngFor="let item of items | async | mapToIterable"
Or process it in your ts file, instead of
this.retJson = this._myService.getData();, use this._myService.getData().subscribe(x => this.retJson = processToArray(x))