【问题标题】:In Angular, how do I avoid a "Property 'json' does not exist on type 'Object'" error?在 Angular 中,如何避免“类型 'Object' 上不存在属性 'json'”错误?
【发布时间】:2019-08-14 21:18:41
【问题描述】:

我正在使用 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"}]

所以我很困惑还有什么可能是错的。

【问题讨论】:

    标签: json angular rest


    【解决方案1】:

    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);
    

    希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-09
      • 2016-05-17
      • 2021-11-12
      • 2018-09-27
      • 2019-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多