3

I have a simple Angular 2 service that is calling a local JSON file. I can get the object to console.log in the .map function in the general.service.ts. However, due to the nature of the async call I cannot seem to print out a single key or value from the object. here is my code.

I understand that I need to include the *ngIf because it is async. However even though I have used the ngIf with the 'generalInfo' which references the component.ts

general.service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { General } from '../interfaces/general.interface'

@Injectable()
export class GeneralService {
  private dataAPI = '../../assets/api.json';

  constructor(private http: Http) {

  }

  getGeneralData() : Observable<General> {
    return this.http.get(this.dataAPI)
      .map((res:Response) => { res.json(); console.log(res.json())})
      .catch((error:any) => Observable.throw(error.json().error ||     'Server error'));
  }
}

header.component.ts

import { Component, OnInit, DoCheck } from '@angular/core';
import 'rxjs/add/operator/map';
import { GeneralService } from '../../services/general.service';

@Component({
  selector: 'header',
  templateUrl: `./header.component.html`
})

export class headerComponent implements OnInit{

  public generalInfo : any;
  public name : string;

  constructor(
    private headerblock: GeneralService
  ) {}

  //Local Properties
  header;

  loadHeader() {
    this.headerblock.getGeneralData()
      .subscribe(
        generalInfo => {
          this.generalInfo = generalInfo;
          this.name = this.generalInfo.name
        },
        err => {
          console.log(err);
        }
      );

  }

  ngOnInit() {
    this.loadHeader();
  }
}

header.component.html

<div class="container">
  <div *ngIf="generalInfo">
     {{name}}
  </div>
</div>

With this code though at the moment - it does not go into the if statement. I'm not sure why this does not work?

Sam Kelham
  • 1,357
  • 4
  • 15
  • 28

1 Answers1

4

*ngIf isn't executed, cause of your map-function doesn't return something.

So within your subscribe-function the incoming value is undefined!

You have to return something within your map-function:

.map((res:Response) => { console.log(res.json()); return res.json(); })

And in your template, use it like this:

{{ generalInfo.name }}

Assuming that generalInfo has a property named name.

slaesh
  • 16,659
  • 6
  • 50
  • 52