Fearghal
Fearghal

Reputation: 11447

Angular 2: Get JSON content from HTTP response

I have received a JSON object (i think) from my HTTP Web Service but struggling to pull out the strings.

https://jsonplaceholder.typicode.com/posts/1 gives me

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

My code: I set up a service:

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

@Injectable()
export class MyNewServiceService {

  constructor(private http: Http) {}
      getHTTP() {
        return this.http.get('https://jsonplaceholder.typicode.com/posts/1').map(
          response =>  response.json());
  }
}

Called it from my app.component, trying and failing tooutput to the screen via title.

import { Component} from '@angular/core';
import { MyNewServiceService } from './my-new-service.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [MyNewServiceService]
})
export class AppComponent {
  title = 'app works!';

  constructor(MyNewServiceService: MyNewServiceService){
    MyNewServiceService.getHTTP()
      .subscribe(
        JSONtitle => this.title = JSONtitle,
        error => console.error('Error: ' + error),
        () => console.log('Completed!')

      );
  }
}

I ended up outputting [object Object] to the screen.

I tried outputting it to console but got 'undefined' assuming service hadn't finished yet in angular2 lifecycle. So i created a new class and tried to cast with it but no luck

export class JsonResponseClass {
    constructor(
    public userid:number,
    public id:string,
    public title:string,
    public body:string
    )
    {}
}

Template is simple...

<h1>
  {{title}}
</h1>

How do i get my strings from the json?

Upvotes: 2

Views: 6360

Answers (1)

seidme
seidme

Reputation: 13058

You're returning response body as a mapping result from the service. Suiting the situation, you can access needed properties in your component as follows:

constructor(MyNewServiceService: MyNewServiceService){
  MyNewServiceService.getHTTP()
    .subscribe(
      resBody => this.title = resBody.title,
      error => console.error('Error: ' + error),
      () => console.log('Completed!')
    );
}

Btw, convention tells us to keep instance variables camelCased, so you can differentiate instance from the class itself:

constructor(private myNewServiceService: MyNewServiceService){
  myNewServiceService.getHTTP()
    .subscribe(
      resBody => this.title = resBody.title,
      error => console.error('Error: ' + error),
      () => console.log('Completed!')
    );
}

Upvotes: 4

Related Questions