Не удалось передать данные службы компоненту - PullRequest
0 голосов
/ 11 октября 2018

Я пытаюсь передать массив, который существует в службе, компоненту, сейчас я получаю результат '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) ;Я получаю результат undefined

Я отправляю ответ, полученный от сервера

{
    "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 голосов
/ 11 октября 2018

Неправильная реализация для вызова службы и метода из компонента.Вы не возвращаете ничего из сервисного уровня, поэтому получаете undefined .

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

Вызов с компонента, как это:

let sports = [];

this._SportsService.getDataa(this._urll)
      .subscribe((response) => {
        this.sports  = data['articles'];
      console.log(this.sports);
      });
0 голосов
/ 11 октября 2018

Ваш сервисный вызов должен быть таким:

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

, а ваш компонентный вызов:

this._SportsService.getDataa()
    .subscribe(
    data => { this.SportsData = data['articles']; },
    () => {
        console.log('this.SportsData', this.SportsData);
    });
0 голосов
/ 11 октября 2018

Хорошо, так что давайте начнем с самого начала.Ваш сервис должен выглядеть так:

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 метода, чтобы получить это в компоненте.
В этом случае это можно наблюдать, поэтому в компоненте вы можете либо подписаться на него, либо изменить с помощью конвейерных операторов.

0 голосов
/ 11 октября 2018

getDataa () является методом: void и ничего не возвращает, он просто подписывается на http-запрос и console.logging данные из http get.

Вам нужно будет что-то вернуть изМетод getDataa (), желательно как наблюдаемый, чтобы вы могли подписаться на него в своем компоненте.

В настоящее время, даже если вы возвращаете данные из getDataa (), у вас все еще может быть проблема с синхронизацией, потому что нет гарантии, чтоngOninit в вашем компоненте будет запущен после завершения http-запроса .... один из способов решения этой потенциальной проблемы с синхронизацией заключается в возврате obersvable для вашего http get и подписке на него, чтобы ваша переменная this.SportsData могла быть обновлена ​​в подписке, когдаhttp get завершен.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...