0

I want to get data from Riot API and display it in html view. However, i can not "hold" this data in my variable. Console log show empty array. I can see json data only in function scope. I guess, i didn`t use observable function corretly, am i wrong? Here is my component.

    import { Component, OnInit } from '@angular/core';
import { FRIEND } from '../../services/_friends/mock-friends';
import { APIKEY } from '../../services/_lolapi/apikey';
import { Http, Response } from '@angular/http';
import { KeysPipe } from '../../pipes/key';
import { JsonPipe } from '@angular/common';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
@Component({
  selector: 'app-friends',
  templateUrl: './friends.component.html',
  styleUrls: ['./friends.component.css']
})
export class FriendsComponent implements OnInit {
friends = FRIEND;
apikey = APIKEY;
nick: string[];
query: string;

  private apiUrl =
  'https://eun1.api.riotgames.com/lol/summoner/v3/summoners/by-name/';
  data: Array<string> = [];

  constructor(private http: Http) {



   }

getFriendData(query) {

return this.http.get(query)
  .map((res: Response) => res.json());

}
getContacts() {
  this.getFriendData(this.query).subscribe(data => {

    this.data = data;
    console.log(this.data);

  });
}


  ngOnInit() {
    for (let i of this.friends) {
        this.query = `${this.apiUrl}${i.nick}${this.apikey}`;
  this.getFriendData(this.query);
   this.getContacts();
console.log(i.nick);
    }
  }

}
1
  • You never subscribe to the observable returned from your getFriendData method, therefore the http request never runs. This is called a cold observable. You have to subscribe to fire the api request. Here is an article on hot vs cold observables. Commented Jan 24, 2018 at 20:24

1 Answer 1

1

You don't need this.getFriendData(this.query) in ngOnInit as in the next line you call getContacts that wraps getFriendData.

Now, your API returns SummonerDTO - a complex object and you are trying to store it as an Array? That doesn't seem right. Additionally, it think you want to store every result in an array, right? In that case you should rather use:

this.data.push(data);
Sign up to request clarification or add additional context in comments.

1 Comment

It`s working! Big thanks for your advice. I cleaned my mess with functions, as you said. And of course, pushed data into array just work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.