我正在使用 Angular 7 并尝试从 Rails 5 应用程序读取 JSON 数据。我的 src/app/app.component.ts 文件中有这个
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
books;
constructor(private http: HttpClient) {
http.get('http://localhost:3000/books.json')
.subscribe(res => this.books = res.json());
}
}
但是,当我使用“ng serve”启动我的 Angular 应用程序时,我收到了这个错误
ERROR in src/app/app.component.ts(15,42): error TS2339: Property 'json' does not exist on type 'Object'.
我已经确认,当我访问 hte 端点http://localhost:3000/books.json 时,我得到了输出
[{"id":1,"name":"Copying and Pasting from Stack Overflow","created_at":"2019-08-14T19:55:57.961Z","updated_at":"2019-08-14T19:55:57.961Z"},{"id":2,"name":"Trying Stuff Until it Works","created_at":"2019-08-14T19:55:57.966Z","updated_at":"2019-08-14T19:55:57.966Z"}]
所以我很困惑还有什么可能是错的。
默认情况下,HttpClient会在幕后为您提取 JSON,而无需使用json()
. HttpModule
在 Angular 2.x 中要求您使用 提取json()
,但HttpClient
在 4.x+ 中为您执行此操作。您可以简单地直接访问解析后的 JSON 数据subscribe()
:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
books;
constructor(private http: HttpClient) {
http.get('http://localhost:3000/books.json')
.subscribe(res => this.books = res);
}
}
真的建议您利用 TypeScript 并对响应进行类型检查:
interface Book {
someProperty: string;
anotherProperty: number;
}
// ...
books: Book[];
// ...
http.get<Book[]>('http://localhost:3000/books.json')
.subscribe(res => this.books = res);
希望这有帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句