【问题标题】:Angular 7 Trying to make 2 http get requests in same *ngForAngular 7 试图在同一个 *ngFor 中发出 2 个 http get 请求
【发布时间】:2019-01-11 10:37:34
【问题描述】:

我正在尝试发出 2 个 GET 请求并在 *ngFor 中使用它,是否有任何解决方案或文档来解决它? 我已经为 GET、POST、UPDATE 和 REMOVE 制作了一个服务 api 使用服务我在我的 REST 服务上调用这些方法。

我只是从这个组件服务(SuperheroService)推送链接

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

超级英雄组件:

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">

【问题讨论】:

  • 欢迎来到 SO!请记住包含Minimal, Complete, and Verifiable example。比如到目前为止你尝试了什么,失败了什么,你做了什么研究。
  • 请提供更多详细信息,至少是失败的模板的一部分以及进行 api 调用的组件内的代码。不可能指望有人用这么少的信息来帮助你。
  • 模板(或组件)不应进行 任何 HTTP 调用,因此不清楚您在问什么。

标签: angular rxjs


【解决方案1】:

你想要一个 forkJoin

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多