Home > Back-end >  How to pass async data from service to component in Angular2
How to pass async data from service to component in Angular2

Time:10-20

I'm using services to get some image URLs using API. When I want to pass this data to other components, I can not do it because passing processing doesn't wait to async data. What should I use to pass this bikeImgs array properly?

This is my service component. I'm pushing respectively the image URLs from API.

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

@Injectable()
export class ItemService {

  bikeImgs :string[] = [];

  constructor(private http: HttpClient) {
    this.http
      .get(
        "https://api.unsplash.com/collections/iuAONw1hf3k/photos/?query=''&per_page=20&client_id=wjJ9ECR9hrNPSx6HMZADgO7D0lWw_kXHPHfyyMMxy2Y&page=1"
      )
      .subscribe((data: any) => {
        data.map((e: any) => {
          this.bikeImgs.push(e.urls.small);
        });
      });
   }

}

This is my component which I want to get the data and see in the console.log

import { Component, OnChanges, OnInit } from '@angular/core';
import { ItemService } from './item.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  bikeImgs: string[] = [];

  constructor(private itemService: ItemService) {
  }

  ngOnInit() {
    this.bikeImgs = this.itemService.bikeImgs;
    console.log("here "  this.bikeImgs);
  }
}

And here is stackblitz project which I created from the above code.

https://stackblitz.com/edit/angular-http-client-first-example-haxfcp?

CodePudding user response:

Return Observable directly to the component

@Injectable()
export class ItemService {
  bikeImgs: string[] = [];

  constructor(private http: HttpClient) {}

  getImages() {
    return this.http
      .get(
        "https://api.unsplash.com/collections/iuAONw1hf3k/photos/?query=''&per_page=20&client_id=wjJ9ECR9hrNPSx6HMZADgO7D0lWw_kXHPHfyyMMxy2Y&page=1"
      )
      .pipe(map((data: any[]) => data.map((item) => item.urls.small)));
  }
}


export class AppComponent implements OnInit {
  bikeImgs: string[] = [];

  constructor(private itemService: ItemService) {}

  ngOnInit() {
    this.itemService.getImages().subscribe((images) => {
      this.bikeImgs = images;
      console.log('here '   this.bikeImgs);
    });
  }
}

https://stackblitz.com/edit/angular-http-client-first-example-rudmgj?file=src/app/app.component.ts

  • Related