简体   繁体   中英

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: 在此处输入图片说明

Thank you!

Looks like your response object has the "title" of the type array ( array[1] ), that's 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

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 ..."}];

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM