Angular 7 Попытка заставить 2 http получить запросы в одном * ngFor - PullRequest
0 голосов
/ 11 января 2019

Я пытаюсь сделать 2 запроса на получение от api и вставить его в * ngFor, любое решение или документы для его решения? я alrady сделал сервис 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 голосов
/ 11 января 2019

Вам нужна вилкаДжоин

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;
                    })
                })
    });
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...