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