gpt4 book ai didi

json - json 的 Angular 5 [object Object] 错误

转载 作者:太空狗 更新时间:2023-10-29 18:15:13 25 4
gpt4 key购买 nike

我正在尝试使用 Angular 5 中的 get 通过 httpclient 加载 json 数据。我正在使用服务、接口(interface)、组件和 json 文件;我已经按照一些教程尝试让它工作,并用 jsonlint 验证了我的 json .据我所知,一切都应该正常运行,json 应该被解析,一切都应该没问题,除了我每次都在控制台中收到 'error: [object Object]' .我尝试了各种方法来修复它,例如

data => this.jsonArticles = Object.values(data);
this.articles = data[0];

但我无法将我的数据转换成任何其他形式。

文章.service.ts

import { Injectable } from '@angular/core';
import { Article } from './article';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class ArticleService {

// Variables
private _jsonUrl: string = './assets/data.json';

// Constructors
constructor(private http: HttpClient) { }

// Methods
getArticles(): Observable<Article[]> {
return this.http.get<Article[]>(this._jsonUrl);
}

}

article.component.ts

import { Component, OnInit } from '@angular/core';
import { ArticleService } from '../article.service';
import { Article } from '../article';

@Component({
selector: 'app-article',
templateUrl: './article.component.html',
styleUrls: ['./article.component.scss']
})
export class ArticleComponent implements OnInit {

// Variables
public jsonArticles = [];
public errorMsg;
// Consturctors
constructor(private _articleService: ArticleService) { }

// Methods
ngOnInit(){
this._articleService.getArticles()
.subscribe(
data => this.jsonArticles = data,
error => this.errorMsg = error);
}
}

文章.ts

export interface Article {
id: number;
author: string;
title: string;
content: string;
tags: string[];
categories: string[];
publishDate: string;
published: boolean;
}

data.json

 [
{
"id": 3,
"author": "",
"title": "Fancy Meat",
"content": "Strip steak bresaola capicola tail cow chicken corned beef turkey.",
"tags": ["test", "lorum"],
"categories": ["blah"],
"publishDate": "2018-02-12T08:15:00.000-05:00",
"published": true
},
]

为简洁起见,我截断了 json 文件,文件中有更多条目使我的 json 对象成为一个数组,并且 json 数组中最后一个条目后没有逗号。

最佳答案

我收到此错误是因为我忘记将 HttpClientModule 导入 app.module.ts 并将其声明到 imports

...
import { HttpClientModule } from '@angular/common/http';

@NgModule({
declarations: [
...
],
imports: [
BrowserModule,
FormsModule,
AppRouteModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

关于json - json 的 Angular 5 [object Object] 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49604496/

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