【发布时间】:2018-10-07 08:36:51
【问题描述】:
我正在做一个项目 ->
**
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.
** 我创建了一个组件文件,即将从服务中获取数据 我尝试使用下面的代码
component.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>
但问题是我无法在浏览器中显示数据
【问题讨论】:
标签: angular angular5 angular6 angular-services