我想从http://quotes.stormconsultancy.co.uk/quotes.json这个URL获取数据。该URL给了我JSON格式的数据。
这是我的 data.services.ts 文件:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
getQuotes(){
return this.http.get('http://quotes.stormconsultancy.co.uk/quotes.json');
}
}
这是我的 home.component.ts 文件:
import { DataService } from './../data.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
quotes: Object;
constructor( private data: DataService ) { }
ngOnInit() {
this.data.getQuotes().subscribe(data =>{
this.quotes = data;
console.log(data);
});
}
}
我已经尝试过 home.component.html 文件中的以下代码:
<div class="container-fluid">
<div class="row">
<div *ngIf="quotes">
<div *ngFor="let quote of quotes.data">
<p>{{ quote.author }} {{ quote.quote}}</p>
</div>
</div>
</div>
</div>
使用此数据后,不会显示在主屏幕上。
答案 0 :(得分:0)
尝试修改您的data.service.ts
文件:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
public getQuotes(): Observable<any> {
return this.http.get("http://quotes.stormconsultancy.co.uk/quotes.json")
.map((res:any) => res);
}
}
答案 1 :(得分:0)
我已经看到了给定API的响应。如下所示:
[{
"author": "Bill Sempf",
"id": 44,
"quote": "QA Engineer walks into a bar. Orders a beer. Orders 0 beers. Orders 999999999 beers. Orders a lizard. Orders -1 beers. Orders a sfdeljknesv.",
"permalink": "http://quotes.stormconsultancy.co.uk/quotes/44"
}, {
"author": "Phil Karlton",
"id": 43,
"quote": "There are only two hard things in Computer Science: cache invalidation, naming things and off-by-one errors.",
"permalink": "http://quotes.stormconsultancy.co.uk/quotes/43"
},
您只需要从html中删除.data。
home.component.html文件:
<div class="container-fluid">
<div class="row">
<div *ngIf="quotes">
<div *ngFor="let quote of quotes">
<p>{{ quote.author }} {{ quote.quote}}</p>
</div>
</div>
</div>
</div>
如果不成功,请检查此。类似评论中提到的Najam us saqib的报价。如果不是数组,请使用map函数。