Vinod Bhavnani
Vinod Bhavnani

Reputation: 2225

My angular 2 object is printed on console, but individual properties are not being printed from the template

Here is my template and component code

Template:

<div *ngIf="newJobCreated">
        <h3>Name: {{newJob.name}}</h3>
        <h3>Job: {{newJob.job}}</h3>
        <h3>ID: {{newJob.id}}</h3>
        <h3>Created At: {{newJob.createdAt}}</h3>
</div>

Component code:

export class StockSearch {
    employeeName:string;
    employeeJob:string;
    employeeData = new Object();
    newJob: Object;
    newJobCreated: boolean

    constructor(public stockService:StocksService) {
        this.newJobCreated = false
    }

    createJob(){
        this.employeeData = {
            "name" : this.employeeName,
            "job" : this.employeeJob
        }
        this.stockService.postJson('https://reqres.in/api/users',this.employeeData).subscribe(
            (data) => {
                this.newJob = data._body
                console.log(data)
                console.log(this.newJob)
                this.newJobCreated = true
            },
            (err) => console.log('Error!',err)

        )
    }
}

My console prints the object as such when I do console.log(this.newJob). Something like {"name":"Vinod ","job":"Gandhi","id":"4","createdAt":"2017-05-26T08:43:21.476Z"}

But if you look at my template, those individual values are not being printed out.

Please help.

Upvotes: 1

Views: 52

Answers (1)

AVJT82
AVJT82

Reputation: 73337

You are getting the string value of your response when you are doing:

this.newJob = data._body

You should get the JSON instead, so fast, easy fix is:

this.newJob = data.json()

I would though use map as well in the service:

Service:

postJson(....) {
  return this.http.(...)
    .map(res => res.json())
}

and then in component

.subscribe(data => {
   this.newJob = data;
   this.newJobCreated = true;
})

Upvotes: 1

Related Questions