Задать вопрос
@Speakermen

Как получить сразу 2 объекта api?

Не знаю насколько правильно формировать так json на сервере
import { MenuService } from './../shared/services/menu.service';
import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  ParseIntPipe,
  DefaultValuePipe,
  Query,
} from '@nestjs/common';
import { Albums as AlbumsModel } from '@prisma/client';
import { AlbumsService, CreateAlbumDto, UpdateAlbumDto } from './index';

@Controller('albums')
export class AlbumsController {
  private album = [];
  private menu = [];

  public constructor(
    private readonly albumsService: AlbumsService,
    private readonly menuService: MenuService,
  ) {}

  @Post()
  public create(@Body() createAlbumDto: CreateAlbumDto) {
    return this.albumsService.create(createAlbumDto);
  }

  @Get()
  public async findAll(
    @Query('skip', new DefaultValuePipe(0), ParseIntPipe) skip: number,
    @Query('take', new DefaultValuePipe(9), ParseIntPipe)
    take: number /*: Promise<AlbumsModel[]> {
    return await this.albumsService.findAll({
      skip,
      take,
    });*/,
  ) {
    this.album = await this.albumsService.findAll({
      skip,
      take,
    });

    this.menu = await this.menuService.findAll();

    return {
      albums: this.album,
      menu: this.menu,
    };
  }

  @Get(':id')
  public findOne(@Param('id') id: string) {
    return this.albumsService.findOne(+id);
  }

  @Patch(':id')
  public update(
    @Param('id') id: string,
    @Body() updateAlbumDto: UpdateAlbumDto,
  ) {
    return this.albumsService.update(+id, updateAlbumDto);
  }

  @Delete(':id')
  public remove(@Param('id') id: string) {
    return this.albumsService.remove(+id);
  }
}


Есть json

{
    "albums": [
        {
            "id": 1,
            "image": "http://placeimg.com/350/315",
            "countTrack": 2,
            "title": "Human Quality Manager"
        },
        {
            "id": 2,
            "image": "http://placeimg.com/350/315",
            "countTrack": 7,
            "title": "National Interactions Technician"
        },
        {
            "id": 3,
            "image": "http://placeimg.com/350/315",
            "countTrack": 4,
            "title": "Internal Communications Executive"
        },
        {
            "id": 4,
            "image": "http://placeimg.com/350/315",
            "countTrack": 1,
            "title": "National Assurance Manager"
        },
        {
            "id": 5,
            "image": "http://placeimg.com/350/315",
            "countTrack": 5,
            "title": "Investor Applications Manager"
        },
        {
            "id": 6,
            "image": "http://placeimg.com/350/315",
            "countTrack": 7,
            "title": "Legacy Communications Administrator"
        },
        {
            "id": 7,
            "image": "http://placeimg.com/350/315",
            "countTrack": 9,
            "title": "Corporate Identity Representative"
        },
        {
            "id": 8,
            "image": "http://placeimg.com/350/315",
            "countTrack": 11,
            "title": "Legacy Directives Coordinator"
        },
        {
            "id": 9,
            "image": "http://placeimg.com/350/315",
            "countTrack": 4,
            "title": "International Security Producer"
        }
    ],
    "menu": [
        {
            "id": 1,
            "path": "/",
            "title": "Home"
        },
        {
            "id": 2,
            "path": "/albums",
            "title": "Albums"
        },
        {
            "id": 3,
            "path": "/contact",
            "title": "Contact"
        }
    ]
}


Как получить album и меню

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Album, AlbumService, Param } from '../../index';

@Component({
  selector: 'app-album',
  templateUrl: './album.component.html',
  styleUrls: ['./album.component.css'],
})
export class AlbumComponent implements OnInit {
  public albums?: Album[];
  public error: any;
  private params!: Param;

  constructor(
    private readonly albumService: AlbumService,
    private readonly route: ActivatedRoute
  ) {}

  public findAll() {
    this.albumService.findAll(this.params).subscribe(
      //(data: Album[]) => (this.albums = data),
      (data: any) => ((this.albums = data.albums), (this.menu = data.menu)),  //  работает
/*
(data: Album[], data: any) => (
        (this.albums = data.albums), (this.menu = data.menu) не работает
      ),
*/
      (error: any) => {
        this.error = error.message;
        console.error(error);
      }
    );
  }

  private getQueryParams(): void {
    this.route.queryParams.subscribe((params: Params) => {
      this.params = {
        skip: params['skip'],
        take: params['take'],
      };
    });
  }

  public ngOnInit(): void {
    this.getQueryParams();
    this.findAll();
  }
}


import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Album, Param } from '../index';

@Injectable({
  providedIn: 'root',
})
export class AlbumService {
  private apiUrl: string;

  public constructor(private readonly http: HttpClient) {
    this.apiUrl = 'http://localhost:8000/api/';
  }

  /*
  public findAll(params: Param): Observable<Album[]> {
    return this.http.get<Album[]>(
      `${this.apiUrl}albums/?skip=${params.skip}&take=${params.take}`
    );
  }
  */

  public findAll(params: Param): Observable<any[]> {
    return this.http.get<any[]>(
      `${this.apiUrl}albums/?skip=${params.skip}&take=${params.take}`
    );
  }
}
  • Вопрос задан
  • 56 просмотров
Подписаться 1 Простой Комментировать
Решения вопроса 1
@kttotto
пофиг на чем писать
(data: any) => ((this.albums = data.albums), (this.menu = data.menu)),

Что за странный синтаксис, что Вы этим хотите?
Почему не написать обычно?
(data: any) => {
    this.albums = data.albums;
    this.menu = data.menu;
}

public ngOnInit(): void {
this.getQueryParams();
this. findAll();
}

И, кстати, это не совсем верно. Метод findAll зависит от this.params который инициализируется в getQueryParams. А findAll начнет выполняться раньше, чем выполнится getQueryParams.
Их нужно запихнуть в pipe
this.route.queryParams
    .pipe(
        mergeMap((params: Params) => {
            this.params = {
                skip: params['skip'],
                take: params['take'],
            };
            return this.albumService.findAll(this.params)
        ),
        tap((data: any) => {
            this.albums = data.albums;
            this.menu = data.menu;
        }),
        catchError(error => {
            this.error = error.message;
            console.error(error);
            return EMPTY;
        })
    })
    .subscribe();
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы