为什么不使用 Angular 显示数据?



我在显示数据时遇到了一些问题。当我提出请求时,它似乎在检索数据,但我不确定我是否正确地利用了它,因为每当我提出获取请求时,都不会显示任何内容。如有任何建议,不胜感激。

api.service.ts:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map, retry, tap } from 'rxjs/operators';
import { Story } from './data';
@Injectable({
providedIn: 'root'
})
export class APIService {
data: Story[] = [];
Base_URL ="https://hacker-news.firebaseio.com/v0/item/8863.json?print=pretty";
constructor(private http: HttpClient) { }
getStories(): Observable<Story> {
return this.http.get<any>(this.Base_URL).pipe(
map((response: any) => { return response['data'] as Story }),
tap((_: Story) => { console.log('Details: {{data}}') })
) 
}
}

news-stories.component.ts:

import { Component, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { APIService } from '../api.service';
import { Story } from '../data';
@Component({
selector: 'app-news-stories',
templateUrl: './news-stories.component.html',
styleUrls: ['./news-stories.component.css']
})
export class NewsStoriesComponent implements OnInit {
data: Story = {by : '', descendants : '', id : '', kids : [ ], score : '', time : '', title : '', type : '', url : ''};
subscriptions: Subscription[] = [];
constructor(private APIService: APIService) { }
ngOnInit(): void { }
get() {
this.subscriptions.push(
this.APIService.getStories()
.subscribe((story: Story) => { this.data = story })
);
}
}

news-stories.component.html:

<div>
<button class="mat-stroked-button" (click) = get()> Get</button>
</div>
<div *ngFor="let item of data | keyvalue">
<p>{{item.key}} : {{item.value}}</p>
</div>

data.ts:

export interface Story {
by : string;
descendants : string;
id : string;
kids : [ ],
score : string;
time : string;
title : string;
type : string;
url : string;
}

您的代码很好,唯一的问题是在map中,您期望得到response.dataresponse['data'],响应没有该属性,将其保留为:

getStories(): Observable<Story> {
return this.http.get(this.Base_URL).pipe( // you don't need to add .get<any>, your function already is saying the return type <Story>
map((response: any) => response as Story), // you don't need curly brackets, and the keyword return
tap((_: Story) => console.log('Details: {{data}}')) //same here
) 
}

最新更新