在将服务数据放入组件中面临的问题

时间:2018-10-06 20:43:36

标签: angular angular5 angular6 angular-services

我正在一个项目中->

**

  

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>
  

但是问题是我无法在浏览器中显示数据

2 个答案:

答案 0 :(得分:0)

您的代码中有许多错误的角度概念。

  • 使用ngOnInit在服务中执行请求的方式 服务
  • 使用throwData函数公开数据的方式

I recommend you reading the angular documentation about services.

话虽这么说,让我尽力帮助您

您的服务应类似于:

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);
  }
}

现在,您只是在订阅服务返回到组件中的情况。

最后一个更改是在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>

我没有测试它,但这应该可以工作,或者至少可以指导您找到解决方案。干杯。

答案 1 :(得分:0)

在服务中使用以下代码,只需使用http注入即可执行请求 它会返回一个observable,然后只需在您的组件中订阅该Observable即可。

@Injectable({
  providedIn: 'root'
})
export class NewsService {

  constructor(private http: HttpClient) {
  }
  fetchDataFromServer(){
      this.http.get('https://newsapi.org/v2/top-headlines?sources=google-news- 
     in&apiKey=5a43238c7827436b9aac37e85583b74a')\
  }
}

Component.ts

@Component({
  selector: 'app-footer',
  templateUrl: './footer.component.html',
  styleUrls: ['./footer.component.css']
})
export class FooterComponent implements OnInit {

  newData$: Observable<any[]>;

  constructor(private _NewsService: NewsService ) { }

  ngOnInit() {

   this.newData$ = this._NewsService.fetchDataFromServer();

  }

}

然后在HTML模板中使用此可观察对象显示信息

<div class="col-md-9 each-blog" *ngFor="let item of newData$ | async">
</div>