0

I am new to angular, I am trying to consume below api http://jsonplaceholder.typicode.com/albums

album.ts

export interface Album {
    userId: number;
    id: string;
    title: string;
}

book.component.ts

import { Component, OnInit } from '@angular/core';
import { BookservService } from '../common/bookserv.service';
import { Album } from './album';


@Component({
  selector: 'app-book',
  templateUrl: './book.component.html',
  styleUrls: ['./book.component.scss']
})
export class BookComponent implements OnInit {
  albums:Album;

  constructor(private serv:BookservService) { }

  ngOnInit() {
    this.serv.getAll()
     .subscribe(
       (value)=>{ 
         console.log(value);         
         this.albums=value;        
        },
       (error)=> console.log(error))
  }

}

bookserv.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { DataService } from "./dataserv";

@Injectable({
  providedIn: 'root'
})
export class BookservService extends DataService {

  constructor(http:HttpClient) {
    super("http://jsonplaceholder.typicode.com/albums",http)
   }
}

dataserv.ts

import { HttpClient } from "@angular/common/http";
import { catchError } from "rxjs/operators";
import { Observable, of } from "rxjs";
import { Album } from '../book/album';


export class DataService {

  constructor(private url: string,private http:HttpClient) {}
    
  getAll():Observable<Album> {
        return this.http.get<Album>(this.url)
        .pipe(catchError(
            (err: any, caught: Observable<Album>) => {
                console.log(err);
                return caught;
            }));
  }
 
}

console.log

(100) [{…},  {…}]
0: {userId: 1, id: 1, title: "quidem molestiae enim"}
1: {userId: 1, id: 2, title: "sunt qui excepturi placeat culpa"}
2: {userId: 1, id: 3, title: "omnis laborum odio"}  etc..

albums is declared as object, but how array of objects directly assigned to object through below line without error

this.albums=value;

At that same time if I declare album as array albums:Album[]=[]; it throws error!!!

could anyone help me to understand

2 Answers 2

1

In your dataserv.ts, update the return signature to return an array of Album

export class DataService {
    constructor(private readonly http: HttpClient) {}
  
    public getAll(url: string): Observable<Album[]> {
      return this.http.get<Album[]>(url).pipe(
        catchError((err, caught) => {
          console.log(err);
          return caught;
        })
      );
    }
  }
}

In your book.component.ts, initialize albums to an empty array.

public albums:Album[] = [];
Sign up to request clarification or add additional context in comments.

Comments

0

inside your data.service.ts you can transforum your responsedata in your getAll http request like this

export class DataService {
  constructor(private readonly http: HttpClient) {}

  // http calls
  getAll(url: string) {
    return this.http.get < albums: any > (url)
      .pipe(map((responseData) => {
        return {
          albums: responseData.albums.map(album => {
            return {
              userId: responsedata.album.userOd,
              id: responsedata.album.id,
              title: responsedata.album.title,
            };
          }),
        };
      }));
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.