繁体   English   中英

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

[英]Facing problem in getting service data into component

我正在一个项目中->

**

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>

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

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

  • 您使用服务的ngOnInit在服务中执行请求的方式
  • 使用throwData函数公开数据的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);
  }
}

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

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

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

在服务中使用以下代码,只需使用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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM