我从HTTP Web服务收到了一个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调用它,尝试并且无法通过标题输出到屏幕。
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中获取字符串?
答案 0 :(得分: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!')
);
}