Angular 7尝试在同一* ngFor中发出2个http get请求

时间:2019-01-11 10:37:35

标签: angular rxjs

我试图从api发出2个获取请求并将其插入* ngFor中,是否有解决方案或文档来解决? 我做一个服务API可以获取,发布,更新和删除 所以通过这个组件服务,我直接连接到它 而且我只是点击了这项优质服务的链接

组件服务

import { Injectable } from '@angular/core';
import { ApiService } from 'src/app/services/api.service';
import { Observable } from 'rxjs';
import {forkJoin} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SuperheroService {

  constructor(private apiService: ApiService) { }
  get() {
    return this.apiService.get('https://jsonplaceholder.typicode.com/users');
  }
  getImgHero(){
    return this.apiService.get('https://jsonplaceholder.typicode.com/photos');
  }

组件TS

import { Component, OnInit } from '@angular/core';
import { SuperheroService } from './superhero.service';

@Component({
  selector: 'app-superhero',
  templateUrl: './superhero.component.html',
  styleUrls: ['./superhero.component.css']
})
export class SuperheroComponent implements OnInit {
heros: any[] = [];
herosImg: any[]= [];
  constructor(private superheroService: SuperheroService) { }

  ngOnInit() {
    this.superheroService.get().subscribe(resp => {
      this.heros = resp;
    });
    this.superheroService.getImgHero().subscribe(Response=>{
    this.herosImg = Response;
    // console.log(Response);

    });
    // this.superheroService.get().subscribe(([res1, res2])=> {
    // this.heros = [res1, res2];
    // });
  }


}

和试图绑定日期的html代码在这里

*ngFor="let hero of heros | slice:0:5; let isFirst = first"  [class.active]="isFirst">

1 个答案:

答案 0 :(得分:0)

您要加入fork

ngOnInit() {
    forkJoin(this.superheroService.get(),
             this.superheroService.getImgHero())
             .subscribe(res)=> {
                //in res[0] you has "heros" and in res[1] you has herosImg
                //I supouse you want to "join"
                //Imagine that hero has "id" and other properties
                //        and heroImg has "id" and "src"
                this.heros = res[0].map(hero=>{
                    let heroImg=res[1].find(heroImg=>heroImg.id==hero.id);
                    return { 
                       ...hero;
                       img:heroImg?heroImg.src:null;
                    })
                })
    });
  }