简体   繁体   English

如何在 Angular2 中将异步数据从服务传递到组件

[英]How to pass async data from service to component in Angular2

I'm using services to get some image URLs using API.我正在使用服务通过 API 获取一些图像 URL。 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?我应该用什么来正确传递这个自行车 Imgs 数组?

This is my service component.这是我的服务组件。 I'm pushing respectively the image URLs from API.我分别从 API 推送图像 URL。

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这是我想要获取数据并在 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.这是我从上面的代码创建的 stackblitz 项目。

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

Return Observable directly to the componentObservable直接返回给组件

@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%2Fapp%2Fapp.component.ts https://stackblitz.com/edit/angular-http-client-first-example-rudmgj?file=src%2Fapp%2Fapp.component.ts

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

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