gpt4 book ai didi

http - Angular 2 : Get JSON content from HTTP response

转载 作者:可可西里 更新时间:2023-11-01 16:27:59 25 4
gpt4 key购买 nike

我从我的 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 中获取我的字符串?

最佳答案

您正在将响应正文作为服务的映射结果返回。根据情况,您可以按如下方式访问组件中所需的属性:

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

关于http - Angular 2 : Get JSON content from HTTP response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42073530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com