JL Pikun JL Pikun - 1 month ago 4x
AngularJS Question

Output array values to template

I'm currently learning Angular 2 and have confused myself with how to output data returned from a service to my template.

My API Response :

"site": {
"success": true,
"title": "foo",
"description": "bar"

My Service :

import { Injectable } from '@angular/core';
import {HTTP_PROVIDERS, Http, Response, Headers, RequestOptions } from "@angular/http";
import { Observable } from 'rxjs/Rx';

export class ContentService {
constructor(private _http:Http) {}

getContent() {
return this._http.get('http://localhost:8080/api/foobar-endpoint/')
.map((res:Response) => res.json())


My Component :

import { Component, OnInit } from '@angular/core';
import { ContentService } from "../../services/content/content.service";

const template = require('./home.jade');
const styles = require('./home.sass');

selector: 'home',
templateUrl: template,
styleUrls: [styles]

export class HomeComponent implements OnInit {

public foo = {}

constructor(private _contentService: ContentService) {}

ngOnInit() {

getContent() {
data => {this.foo = data},
err => { console.log(err) },
() => console.log()


My Template :

p {{ foo.site.title }}

If I place
{{ foo | json }}
in my template I can see the returned values in a JSON format, but when I try and output a single value, such as
I get undefined errors.

How can I access the values being returned?


I think the only thing you are missing here is the ?. Basically the problem is that when the components instantiates your foo property has no site param so angular throws the error.

So what you can do is either this:


Or this:

<p *ngIf="foo.site">{{foo.site.title}}</p>

This way angular won't try to bind the title before there is a site.