我正在尝试使用Angular 5中的get通过httpclient加载json数据。我正在使用服务,接口,组件和json文件;我已经按照一些教程试着让它工作,并用jsonlint验证我的json。从我所看到的,一切都应该起作用,json应该被解析,一切都应该没问题,除非我每次都在控制台中得到 '错误:[object Object]' 。我已经尝试了各种方法来解决它,例如
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
$password2 = $_POST['password1'];
$username2 = $_POST['username1'];
$connection = mysqli_connect("localhost", "root", "password", "database") or die("Unable to connect to MySQL");
$query = mysqli_query($connection, "SELECT * FROM users where username = '$username2' AND password = '$password2'") or die(mysqli_error($connection));
$row = mysqli_fetch_array($query, MYSQLI_BOTH) or die(mysqli_error($connection));
if(!empty($row['username']) AND !empty($row['password'])) {
session_start();
$_SESSION['username'] = $username2;
http_response_code(200);
echo "Successful Login";
exit;
}
else{
http_response_code(403);
echo "The password or username you have entered is not valid";
}
mysqli_close($connection);
?>
但我无法将我的数据转换为任何其他形式。
article.service.ts
data => this.jsonArticles = Object.values(data);
this.articles = data[0];
article.component.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.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);
}
}
data.json
export interface Article {
id: number;
author: string;
title: string;
content: string;
tags: string[];
categories: string[];
publishDate: string;
published: boolean;
}
我为了简洁而截断了json文件,文件中有更多的条目使我的json对象成为一个数组,并且在json数组中的最后一个条目之后没有逗号。
答案 0 :(得分:5)
出现此错误是因为我忘记将HttpClientModule
导入app.module.ts
并将其声明到imports
...
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
...
],
imports: [
BrowserModule,
FormsModule,
AppRouteModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }