angular - 将服务数据导入组件时面临问题
问题描述
我正在做一个项目->
**
1.
** 我创建了一个服务文件 news.service.ts ,(代码如下)**
2.
** 在服务中,我创建了返回服务数据的函数 throwData()
import { Injectable } from '@angular/core';
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class NewsService implements OnInit {
Data: any = [];
constructor(private http: HttpClient) {
}
ngOnInit(): void {
console.log('f: ' );
this.http.get('https://newsapi.org/v2/top-headlines?sources=google-news-in&apiKey=5a43238c7827436b9aac37e85583b74a').subscribe(data => {
this.Data = data['articles'];
console.log('from service = ' + this.Data[0] );
});
}
throwData(): any {
return this.Data;
}
}
**
3.
** 我创建了一个组件文件,该文件即将从我尝试使用以下代码的服务中获取数据
组件.ts 文件
import { Component, OnInit } from '@angular/core';
import {NewsService} from '../service/news.service';
@Component({
selector: 'app-footer',
templateUrl: './footer.component.html',
styleUrls: ['./footer.component.css']
})
export class FooterComponent implements OnInit {
newData: any = [];
constructor(private _NewsService: NewsService ) { }
ngOnInit() {
this.newData = this._NewsService.throwData();
}
}
**
4.
** 创建一个 html 文件以在浏览器 component.html文件中显示数据
<div class="container">
<div class="row">
<div class="col-md-9 each-blog" *ngFor="let item of newData; let i = index" style="margin-top: 17px ; background-color: #e3e0ef ; border-left: 5px solid #3d7e9a; ; cursor: pointer;">
<div>
<div class="col-md-3">
<img class="img" src="{{item.urlToImage}}" />
</div>
<div class="col-md-9">
<a href="{{item.url}}" target="_blank" style="margin-top:0px">{{item.title}}</a>
<p>{{item.content}}</p>
</div>
</div>
</div>
<div class="col-md-3"></div>
</div>
</div>
但问题是我无法在浏览器中显示数据
解决方案
您的代码中有许多角度概念错误。
- 您使用服务的 ngOnInit 在服务中执行请求的方式
throwData
使用函数公开数据的方式
话虽如此,让我试着帮助你:
您的服务应类似于:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class NewsService {
data: any[];
constructor(private _http: HttpClient) {}
getData(): Observable<any[]> {
return !this.data
? this._http
.get(
'https://newsapi.org/v2/top-headlines?sources=google-news-in&apiKey=5a43238c7827436b9aac37e85583b74a'
)
.pipe(
switchMap(data => {
this.data = data['articles'];
return this.data;
})
)
: of(this.data);
}
}
不要在初始化时获取数据,而是创建一个函数,如果数据未定义则请求数据,如果数据已经存在则返回它。
在组件中:
import { Component, OnInit } from '@angular/core';
import { NewsService } from '../service/news.service';
@Component({
selector: 'app-footer',
templateUrl: './footer.component.html',
styleUrls: ['./footer.component.css']
})
export class FooterComponent implements OnInit {
newData: any[];
constructor(private _NewsService: NewsService ) { }
ngOnInit() {
this._NewsService.getData().subscribe(data => this.newData = data);
}
}
现在您只是订阅了服务在组件中返回的 observable。
最后一个更改是在您的 HTML 中,只需在遍历数组之前添加一个 ngIf
<div class="container">
<div class="row">
<div class="col-md-9 each-blog" *ngIf="newData" *ngFor="let item of newData; let i = index" style="margin-top: 17px ; background-color: #e3e0ef ; border-left: 5px solid #3d7e9a; ; cursor: pointer;">
<div>
<div class="col-md-3">
<img class="img" src="{{item.urlToImage}}" />
</div>
<div class="col-md-9">
<a href="{{item.url}}" target="_blank" style="margin-top:0px">{{item.title}}</a>
<p>{{item.content}}</p>
</div>
</div>
</div>
<div class="col-md-3"></div>
</div>
</div>
我没有对其进行测试,但这应该可以工作,或者至少可以指导您找到解决方案。干杯。
推荐阅读
- c# - 迭代代表类型的语法
- javascript - 在反应本机选择器中条件渲染两个 TextInput
- python - 按白天/夜晚对图像进行排序
- javascript - Javascript如何在触发下一个函数之前正确等待一个函数?
- javascript - 当我按 Enter 时转到下一个输入:ng-zorro
- swift - React Native 模块与 Swift UIView 和 .xib 文件
- javascript - 在 sagas 中调用基本函数有什么意义?
- c# - 泛型类型的 Json 模式 $ref 名称随 Swagger 和 OpenApi 更改
- google-sheets - 在二维表中移动/移动项目的公式,以便它们在匹配的一维表项目的同一行中?
- vaadin - 下载的 Vaadin14 图表的分辨率远低于用户屏幕上显示的图表