我正在使用Angular 7,并试图从Rails 5应用程序读取JSON数据。我的src / app / app.component.ts文件中有这个
var input= {
"comment": " notes"
};
var result = JSON.stringfy(input, function(kay,value){
if(value === "string"){
return value.toUpperCase().trim();
}
});
console.log("RESULT ",result);
但是,当我使用“ ng serve”启动Angular应用程序时,出现此错误
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());
}
}
我已经确认,当我访问端点http://localhost:3000/books.json时,我会得到输出
ERROR in src/app/app.component.ts(15,42): error TS2339: Property 'json' does not exist on type 'Object'.
所以我对其他可能出错的地方感到困惑。
答案 0 :(得分:2)
HttpClient默认情况下无需使用json()
即可在后台为您提取JSON。 Angular 2.x中的HttpModule
要求您使用json()
进行提取,但是4.x +中的HttpClient
会为您完成提取。您可以直接在subscribe()
中直接访问已解析的JSON数据:
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和type-check the response:
interface Book {
someProperty: string;
anotherProperty: number;
}
// ...
books: Book[];
// ...
http.get<Book[]>('http://localhost:3000/books.json')
.subscribe(res => this.books = res);
希望有帮助!