2017-02-06 155 views
2

我从HTTP Web服务收到了一个JSON对象(我认为),但努力拔出字符串。Angular 2:从HTTP响应中获取JSON内容

https://jsonplaceholder.typicode.com/posts/1给我

{ 
    "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" 
} 

我的代码: 我设置了一个服务:

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()); 
    } 
} 

从我app.component叫它,试图通过和没有标题来tooutput屏幕。

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!') 

    ); 
    } 
} 

我最终输出[object Object]到屏幕上。

我试着输出它到控制台,但得到'未定义'假设服务尚未完成在angular2生命周期。所以我创建了一个新的类,并试图用它,但没有运气

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

模板是简单的投...

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

如何让我的琴弦从JSON?

回答

4

您将响应正文作为服务的映射结果返回。主动适应形势,您可以在您的组件访问需要的属性如下:

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

顺便说一句,会议告诉我们keep instance variables camelCased,这样你就可以从类本身区分实例:

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