无法将服务数据传递到组件

时间:2018-10-11 13:10:11

标签: angular angular5 angular6 angular-services

我试图将服务中存在的Array传递给Component,现在我在控制台中得到结果'undefined'。当我向组件注入服务并将数据传递给变量,然后将console.log()变量传递给

Service.ts文件

import { Injectable } from '@angular/core';
import { Component, OnInit  } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';

@Injectable()
export class SportsService implements OnInit {
  sports: any = [];
  _urll  = 'https://newsapi.org/v2/top-headlines?country=in&category=sports&apiKey=69e4c9820959482e8c40e42f8bcfe975';

  constructor(private _http: HttpClient) {      }

  getDataa(): void {

    this._http.get(this._urll).subscribe(
      data => { this.sports  = data['articles'];
      console.log(this.sports);


              });
  }

  ngOnInit() { }




}

我要获取数据的组件 component.ts ->

import { Component, OnInit } from '@angular/core';
import {SportsService} from '../service/sports.service';


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

 SportsData: any = [];

    constructor(public _SportsService: SportsService ) {

     }

    ngOnInit() {

      this.SportsData =   this._SportsService.getDataa();

        console.log(this.SportsData);

     }

  }

当我尝试 console.log(this.SportsData)时;我得到的结果未定义

我正在从服务器获取响应

{
    "status": "ok",
    "totalResults": 20,
    "articles": [
        {
            "source": {
                "id": null,
                "name": "Timesnownews.com"
            },
            "author": null,
            "title": "I don't want to spoil a youngster's place because I want to play the World Cup, says Yuvraj Singh",
            "description": null,
            "url": "https://www.timesnownews.com/sports/cricket/article/i-don-t-want-to-spoil-a-youngster-s-place-because-i-want-to-play-the-world-cup/297860",
            "urlToImage": null,
            "publishedAt": "2018-10-11T12:08:08Z",
            "content": null
        },
        {
            "source": {
                "id": null,
                "name": "Businessinsider.in"
            },
            "author": null,
            "title": "Vladimir Putin told Khabib Nurmagomedov's father to cut him some slack after he incited a riot at UFC 229",
            "description": "Mikhail Klimentyev / Sputnik / Kremlin Pool Photo via APRussian President Vladimir Putin, left, meets with Khabib Nurmagomedov, right, who has won the UFC",
            "url": "https://www.businessinsider.in/Vladimir-Putin-told-Khabib-Nurmagomedovs-father-to-cut-him-some-slack-after-he-incited-a-riot-at-UFC-229/articleshow/66164956.cms",
            "urlToImage": "https://www.businessinsider.in/photo/66164956/vladimir-putin-told-khabib-nurmagomedovs-father-to-cut-him-some-slack-after-he-incited-a-riot-at-ufc-229.jpg?100879",
            "publishedAt": "2018-10-11T11:48:59Z",
            "content": "Mikhail Klimentyev / Sputnik / Kremlin Pool Photo via AP Russian President Vladimir Putin, left, meets with Khabib Nurmagomedov, right, who has won the UFC lightweight title, in Ulyanovsk on the Volga River, Russia, Wednesday, Oct. 10, 2018. Putin defended th… [+2662 chars]"
        },
        {
            "source": {
                "id": "the-times-of-india",
                "name": "The Times of India"
            },
            "author": null,
            "title": "Sticky wicket as China crash to 26 all out - again",
            "description": "Cricket News: ​China may have the world's biggest population and the second largest economy, but they are yet to impress in one area: the cricket field, where they",
            "url": "https://timesofindia.indiatimes.com/sports/cricket/news/sticky-wicket-as-china-crash-to-26-all-out-again/articleshow/66164330.cms",
            "urlToImage": "https://static.toiimg.com/thumb/msid-66164466,width-1070,height-580,imgsize-139112,resizemode-6,overlay-toi_sw,pt-32,y_pad-40/photo.jpg",
            "publishedAt": "2018-10-11T11:16:17Z",
            "content": "KUALA LUMPUR: China may have the world's biggest population and the second largest economy, but they are yet to impress in one area: the cricket field, where they have been humbled by minnows Nepal. China's latest foray on the international stage ended in a h… [+1872 chars]"
        },
        {
            "source": {
                "id": "the-times-of-india",
                "name": "The Times of India"
            },
            "author": null,
            "title": "#MeToo Movement: Lankan cricketer Lasith Malinga accused of sexual harassment",
            "description": "Off the field News: The #MeToo movement seems to have entered the cricketing arena too with Chinmayi Sripaada posting a tweet on behalf of an anonymous woman, claiming th",
            "url": "https://timesofindia.indiatimes.com/sports/off-the-field/metoo-movement-lankan-cricketer-lasith-malinga-accused-of-sexual-harassment/articleshow/66164116.cms",
            "urlToImage": "https://static.toiimg.com/thumb/msid-66164088,width-1070,height-580,imgsize-1835039,resizemode-6,overlay-toi_sw,pt-32,y_pad-40/photo.jpg",
            "publishedAt": "2018-10-11T11:03:00Z",
            "content": "NEW DELHI: The #MeToo movement seems to have entered the cricketing arena too with prominent singer Chinmayi Sripaada posting a tweet on behalf of an anonymous woman, claiming that Sri Lankan cricketer Lasith Malinga sexually assaulted the woman during an IPL… [+2043 chars]"
        },
        {
            "source": {
                "id": "the-times-of-india",
                "name": "The Times of India"
            },
            "author": null,
            "title": "Hardik Pandya introduces his new 'Bentley' on 25th birthday",
            "description": "Off the field News: India cricketer Hardik Pandya, who on Thursday turned 25, introduced a new addition to his family - 'Bentley' - through social media platform, Twitter",
            "url": "https://timesofindia.indiatimes.com/sports/off-the-field/hardik-pandya-introduces-his-new-bentley-on-25th-birthday/articleshow/66164131.cms",
            "urlToImage": "https://static.toiimg.com/thumb/msid-66164209,width-1070,height-580,imgsize-1212656,resizemode-6,overlay-toi_sw,pt-32,y_pad-40/photo.jpg",
            "publishedAt": "2018-10-11T10:58:41Z",
            "content": "NEW DELHI: India cricketer Hardik Pandya, who on Thursday turned 25, introduced a new addition to his family - 'Bentley' - through social media platform, Twitter. The flambouyant all-rounder called the new member 'My new Bentley', adding that it is sustainabl… [+1488 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "Ndtv.com"
            },
            "author": "NDTVSports.com",
            "title": "Chelsea FC To Send Racist Fans On Trips To Auschwitz",
            "description": "Chelsea owner, Roman Abramovich, who is Jewish, is at the forefront of the initiative, designed to tackle anti-semitism among fans.",
            "url": "https://sports.ndtv.com/english-premier-league/chelsea-fc-to-send-racist-fans-on-trips-to-auschwitz-1930484",
            "urlToImage": "https://c.ndtvimg.com/2018-10/jl373nmo_chelsea-fans-afp_625x300_11_October_18.jpg",
            "publishedAt": "2018-10-11T10:54:00Z",
            "content": "Chelsea FC have said that they want to send racist supporters on trips to the Nazi concentration camp Auschwitz in Poland instead of imposing ban orders, a media report said on Thursday. The club's owner, Roman Abramovich, who is Jewish, is at the forefront o… [+1169 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "Cricbuzz.com"
            },
            "author": "",
            "title": "Holder, Roach set to return as Windies seek fortune turnaround",
            "description": "Unchanged India chase tenth consecutive series win at home",
            "url": "https://www.cricbuzz.com/cricket-news/104487/windies-tour-of-india-2018-jason-holder-kemar-roach-set-to-return-as-windies-seek-fortune-turnaround",
            "urlToImage": "http://i.cricketcb.com/i/news/stories/2018/oct/11//prv_1539254675.jpeg",
            "publishedAt": "2018-10-11T10:44:00Z",
            "content": "With the first Test finishing in less than three days, the question heading into the Hyderabad Test is: how many days would the Windies last? © AFP During the good old days of Caribbean glory, any loss associated with the West Indies came with the question ho… [+4908 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "Firstpost.com"
            },
            "author": null,
            "title": "India vs West Indies: Prithvi Shaw shouldn't be compared to anyone, give him space to grow, says Virat Kohli",
            "description": "Virat Kohli sought to protect prolific teenager Prithvi Shaw Thursday from the weight of comparisons with India legend Sachin Tendulkar after the young batsman's Test debut century last week.",
            "url": "https://www.firstpost.com/firstcricket/sports-news/india-vs-west-indies-prithvi-shaw-shouldnt-be-compared-to-anyone-give-him-space-to-grow-says-virat-kohli-5359701.html",
            "urlToImage": "https://images.firstpost.com/wp-content/uploads/2018/10/Prithvi-Shaw-ton-Rajkot-Reuters-social.jpg",
            "publishedAt": "2018-10-11T10:04:32Z",
            "content": "Virat Kohli sought to protect prolific teenager Prithvi Shaw Thursday from the weight of comparisons with India legend Sachin Tendulkar after the young batsman's Test debut century last week. Another century in the second match against the Windies which begin… [+3595 chars]"
        },
        {
            "source": {
                "id": "the-times-of-india",
                "name": "The Times of India"
            },
            "author": "Anuj Tiwari",
            "title": "Sundar Singh Gurjar Seals Silver For India In Javelin At Asian Para Games",
            "description": "Indian javelin thrower Sundar Singh Gurjar won a silver medal in the men's F46 category of the Asian Para Games where two-time Paralympic gold-medallist Devendra Jhajharia finished fourth, on Thursday. In the same event, Rinku picked up a bronze medal to make…",
            "url": "https://www.indiatimes.com/sports/sundar-singh-gurjar-seals-silver-for-india-in-javelin-at-asian-para-games-354598.html",
            "urlToImage": "https://media.indiatimes.in/media/facebook/2018/Oct/sundar_singh_gurjar_1539247903_800x420.jpg",
            "publishedAt": "2018-10-11T09:21:16Z",
            "content": null
        },
        {
            "source": {
                "id": "the-times-of-india",
                "name": "The Times of India"
            },
            "author": "Amit Kumar",
            "title": "EXCLUSIVE - Yuzvendra Chahal: MS Dhoni can read bowlers' body language from behind the stumps",
            "description": "Cricket News: Under Mahendra Singh Dhoni's tutelage, many young cricketers have honed their skills in the cricketing arena and the exceptionally talented leg-spinne",
            "url": "https://timesofindia.indiatimes.com/sports/cricket/news/exclusive-yuzvendra-chahal-ms-dhoni-can-read-bowlers-body-language-from-behind-the-stumps/articleshow/66161457.cms",
            "urlToImage": "https://static.toiimg.com/thumb/msid-66161431,width-1070,height-580,imgsize-1123736,resizemode-6,overlay-toi_sw,pt-32,y_pad-40/photo.jpg",
            "publishedAt": "2018-10-11T08:00:28Z",
            "content": null
        },
        {
            "source": {
                "id": null,
                "name": "Thefangarage.com"
            },
            "author": null,
            "title": "Fantasy Kabaddi - Dream 11 tips for Patna Pirates vs UP Yoddha - Pro Kabaddi",
            "description": null,
            "url": "https://thefangarage.com/articles/15574-fantasy-kabaddi--dream-11-tips-for-patna-pirates-vs-up-yoddha--pro-kabaddi",
            "urlToImage": null,
            "publishedAt": "2018-10-11T06:47:44Z",
            "content": null
        },
        {
            "source": {
                "id": null,
                "name": "Indiatoday.in"
            },
            "author": null,
            "title": "Manu Bhaker braces up for the grind ahead: Ready for Tokyo 2020 Olympics",
            "description": "A day after winning the gold, Manu Bhaker was the same smiling self, happy to be in the company of coach Jaspal Rana and other shooters like Sourabh Choudhary.",
            "url": "https://www.indiatoday.in/mail-today/story/manu-bhaker-braces-up-for-the-grind-ahead-ready-for-tokyo-2020-olympics-1360401-2018-10-11",
            "urlToImage": "https://akm-img-a-in.tosshub.com/indiatoday/images/story/201810/manu-bhaker-759-647x363.jpeg?lU.n9WxTqApxOoPqer_gxdemyLOtlvH.",
            "publishedAt": "2018-10-11T06:35:30Z",
            "content": "Manu Bhaker is savouring success after a long time. Not having done well at the Asian Games, the 16-year-old bounced back to win gold in the Youth Olympics air pistol event in Buenos Aires on Tuesday. A day after winning the gold, Manu was the same smiling se… [+2760 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "Cricbuzz.com"
            },
            "author": null,
            "title": "Live Cricket Score of Pakistan vs Australia, 1st Test, Day 5",
            "description": null,
            "url": "https://www.cricbuzz.com/cricket-news/104483/live-cricket-score-of-pakistan-vs-australia-1st-test-day-5",
            "urlToImage": null,
            "publishedAt": "2018-10-11T05:45:42Z",
            "content": null
        },
        {
            "source": {
                "id": null,
                "name": "Yahoo.com"
            },
            "author": null,
            "title": "Bhubaneswar inaugurates the new look Kalinga Stadium",
            "description": null,
            "url": "https://in.news.yahoo.com/bhubaneswar-inaugurates-look-kalinga-stadium-155320187.html",
            "urlToImage": null,
            "publishedAt": "2018-10-11T05:08:28Z",
            "content": null
        },
        {
            "source": {
                "id": null,
                "name": "India.com"
            },
            "author": "Zee Media Bureau",
            "title": "India's SV Sunil suffers knee injury, doubtful for Men's Hockey World Cup",
            "description": "The Indian Men’s Hockey team suffered an injury setback as striker S V Sunil was virtually ruled out of the upcoming World Cup citing a knee injury.",
            "url": "http://zeenews.india.com/hockey/india-s-sv-sunil-suffers-knee-injury-doubtful-for-men-s-hockey-world-cup-2147561.html",
            "urlToImage": "http://ste.india.com/sites/default/files/2018/10/11/727072-sunil.jpg",
            "publishedAt": "2018-10-11T04:59:56Z",
            "content": "zeenews.india.com understands that your privacy is important to you and we are committed for being transparent about the technologies we use. This cookie policy explains how and why cookies and other similar technologies may be stored on and accessed from you… [+7503 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "Ndtv.com"
            },
            "author": "NDTVSports.com",
            "title": "Cristiano Ronaldo Rape Allegations: Juventus Star Insists Sex Was \"Completely Consensual\"",
            "description": "Police in Las Vegas announced last week that they were reopening an investigation into allegations made by a former model, Kathryn Mayorga, relating to an incident in 2009.",
            "url": "https://sports.ndtv.com/football/cristiano-ronaldo-rape-allegations-juventus-star-insists-sex-was-completely-consensual-1930202",
            "urlToImage": "https://c.ndtvimg.com/2018-10/m779dsig_cristiano-ronaldo-juventus-training-afp_625x300_11_October_18.jpg",
            "publishedAt": "2018-10-11T04:23:48Z",
            "content": "Cristiano Ronaldo insisted again on Wednesday that he did not rape a woman he met in a Las Vegas hotel in 2009 and that their sexual encounter was \"completely consensual\", said his lawyer. \"Ronaldo is forced to break his silence,\" said the Juventus and Portug… [+1498 chars]"
        },
        {
            "source": {
                "id": "the-times-of-india",
                "name": "The Times of India"
            },
            "author": "PTI",
            "title": "KL Rahul to get another chance in 2nd Test vs West Indies",
            "description": "Despite 14 failures in 16 Test knocks, Rahul may get another chance in the second Test against the West Indies",
            "url": "https://economictimes.indiatimes.com/news/sports/kl-rahul-to-get-another-chance-in-2nd-test-vs-west-indies/articleshow/66157221.cms",
            "urlToImage": "https://img.etimg.com/thumb/msid-66157253,width-1070,height-580,imgsize-159556,overlay-economictimes/photo.jpg",
            "publishedAt": "2018-10-11T02:11:00Z",
            "content": "Opener KL Rahul is an “outstanding talent” who needs to be “persisted with” but fast bowler Umesh Yadav, who gets frequently dropped after one failure is an “unfortunate” player, according to Indian bowling coach Bharath Arun. Despite 14 failures in 16 Test k… [+2230 chars]"
        },
        {
            "source": {
                "id": "the-times-of-india",
                "name": "The Times of India"
            },
            "author": "PTI",
            "title": "Bullseye: Shooter Saurabh Chaudhary wins gold at Youth Olympics",
            "description": "​​The 16-year-old Chaudhary dominated the final, shooting 244.2 to finish on top of the podium.",
            "url": "https://economictimes.indiatimes.com/news/sports/bullseye-shooter-saurabh-chaudhary-wins-gold-at-youth-olympics/articleshow/66157139.cms",
            "urlToImage": "https://img.etimg.com/thumb/msid-66157152,width-1070,height-580,imgsize-150833,overlay-economictimes/photo.jpg",
            "publishedAt": "2018-10-11T01:50:00Z",
            "content": "Saurabh Chaudhary gunned down the men’s 10m air pistol gold, capping off the Indian shooting team’s campaign at the Youth Olympics on Wednesday in the manner that befits its best-ever showing. The 16-year-old Chaudhary dominated the final, shooting 244.2 to f… [+2574 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "Newindianexpress.com"
            },
            "author": "Express News Service",
            "title": "Indian cricket: Out with old and in with the new or play it safe?",
            "description": "Apparently , there isn’t much to look forward to when the selectors meet on Thursday to pick the Indian team for the one-day series against the West Indies starting on October 21.",
            "url": "http://www.newindianexpress.com/sport/cricket/2018/oct/11/indian-cricket-out-with-old-and-in-with-the-new-or-play-it-safe-1883889.html",
            "urlToImage": "http://images.newindianexpress.com/uploads/user/imagelibrary/2018/10/11/w600X390/Rishabh-Pant-AP.jpg",
            "publishedAt": "2018-10-10T23:06:50Z",
            "content": "CHENNAI: Apparently, there isn’t much to look forward to when the selectors meet on Thursday to pick the Indian team for the one-day series against the West Indies starting on October 21. What’s the big deal about taking on a side as lacklustre as this bunch … [+2624 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "Ndtv.com"
            },
            "author": "NDTVSports.com",
            "title": "Jason Holder Takes A Dig At Critics, Says Team Which Had Brian Lara Couldn't Win In India",
            "description": "The Windies last drew an away Test series against India way back in 1994 when Brian Lara scored 91 at Mohali.",
            "url": "https://sports.ndtv.com/india-vs-west-indies-2018/india-vs-west-indies-jason-holder-takes-a-dig-at-critics-says-team-which-had-brian-lara-couldnt-win-1929978",
            "urlToImage": "https://c.ndtvimg.com/2018-10/niiok12_windies-batsman-dismissal-bcci_625x300_10_October_18.jpg",
            "publishedAt": "2018-10-10T12:53:33Z",
            "content": "The inexperienced West Indies cricket team suffered an inning and 272-run defeat against India in the first Test at Rajkot. India finished the match inside three days as the spinners wrapped up the clueless Windies batsmen twice in four sessions. Post the cru… [+2757 chars]"
        }
    ]
}

4 个答案:

答案 0 :(得分:0)

getDataa()是:void方法,不返回任何内容,它只是订阅http请求和控制台。从http get中记录数据。

您将需要从getDataa()方法返回一些内容,最好以可观察的形式返回,以便您可以在组件中对其进行订阅。

当前,即使您从getDataa()返回数据,也可能会出现计时问题,因为无法保证组件中的ngOninit在http请求完成后便会运行。计时问题是您的http get返回一个observable并订阅它,以便您的变量this.SportsData可以在http get完成后在订阅中更新。

答案 1 :(得分:0)

您的服务电话应为:

getData(){  
    return this._http.get<any>(this._url);
}

和您的组件调用如下:

this._SportsService.getDataa()
    .subscribe(
    data => { this.SportsData = data['articles']; },
    () => {
        console.log('this.SportsData', this.SportsData);
    });

答案 2 :(得分:0)

好吧,让我们从头开始。您的服务应如下所示:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { pluck } from 'rxjs/operators';

@Injectable()
export class SportsService {
  private readonly url  = 'https://newsapi.org/v2/top-headlines?country=in&category=sports&apiKey=69e4c9820959482e8c40e42f8bcfe975';

  constructor(private http: HttpClient) {
  }

  getData = () => this.http.get(this.url).pipe(pluck('articles'));
}

您的组件是这样的:

import { Component, OnInit } from '@angular/core';
import { SportsService } from '../service/sports.service';


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

  sportsData$: Observable<any>;

  constructor(private sportsService: SportsService ) {
  }

  ngOnInit() {
    this.sportsData$ = this.sportsService.getData();
  }

}

您必须从此getData方法返回一些内容才能在组件中接收它。
在这种情况下,它是可以观察到的,因此在组件中,您可以对此进行订阅,也可以通过管道运算符进行修改。

答案 3 :(得分:0)

组件的服务和方法调用的实现不正确。您不会从服务层返回任何内容,因此会得到未定义

  1. 解决问题的第一种方法是直接使用服务中的对象。

    ngOnInit() {
      this.SportsData =   this._SportsService.getDataa();
        console.log(this._SportsService.SportsData);
    }
    
  2. 另一种方法是在组件而不是服务层中定义SportsData并订阅。

在服务中写以下内容:

getDataa(){
    return this._http.get(this._urll)..map((response) => response.json());
  }

像这样从Component调用:

let sports = [];

this._SportsService.getDataa(this._urll)
      .subscribe((response) => {
        this.sports  = data['articles'];
      console.log(this.sports);
      });