2017-02-06 99 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!') 
    ); 
    }