Florin Simion Florin Simion - 1 month ago 8
TypeScript Question

Angular 2 - I can't output my values from JSON (TypeScript)

I'm trying to output a list using *ngFor in Angular 2, but the only way to actualy get something on the screen is to do something like:

<li *ngFor="let node of nodes">{{node | json}}</li>


which of course, will return all the JSON

if I do something like this

<li *ngFor="let node of nodes">{{node.title}}</li>


I will get printed [object Object]

This is how my app.component.ts looks like

import { Component, OnInit } from '@angular/core';
import 'rxjs/add/operator/toPromise';
import { Injectable } from '@angular/core';
import {Http, Headers, Response} from '@angular/http';


@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})


export class AppComponent implements OnInit{

getData: string;
postData: string;
nodes = [{title : "basic page 1", content: "test page in Drupal 8 ..."}, {title : "basic page 2", content: "Another page in Drupal 8 ..."}];

constructor(private http: Http) {
}

ngOnInit() {

this.http.get("http://the-server.co.uk/rest/export/json/basic").
toPromise().then(r => r.json()).then(r => this.nodes = r);
}
}


This is how my Objects are looking in console:
enter image description here

Thank you!

Answer

Looks like your response object has the "title" of the type array. (array[1]), thats the reason you are seeing {object,object} printed. you can try expanding the "title" and put that in the template. {{node.title."titiledummy"}}

http://plnkr.co/edit/a9k3wDbaKFIfYqWgf78x?p=preview

Blockquote

import { Component, OnInit } from '@angular/core';

@Component({ selector: 'my-app', template: <li *ngFor="let node of nodes">{{node.title[0].key}}</li> })

export class AppComponent implements OnInit{

private nodes = [{title : "basic page 1", content: "test page in Drupal 8 ..."}, {title : "basic page 2", content: "Another page in Drupal 8 ..."}];

constructor() { }

ngOnInit() { this.nodes = [{title : [{'key':"basic page 1"}], content: "test page in Drupal 8 ..."}, {title : [{'key':"basic page 2"}], content: "Another page in Drupal 8 ..."}];

}

Blockquote

Comments