How to return a list of objects created based on interface?

  angular, javascript, typescript

At the moment I have a service that should return the id and the name of the books:

@Injectable({
    providedIn: 'root',
})
export class ApiFetcher {
    constructor(private http: HttpClient) { }

 async getBooksListNames() {
        let books = await this.http.get<Book[]>("https://www.anapioficeandfire.com/api/books").toPromise();
        let booksNames = books.map(function (book) { return { name: book.name, id: book.url.substr(book.url.lastIndexOf("/") + 1) } });

        return booksNames;
    }
}

I call it here:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(
    private apifetcherService: ApiFetcher
  ) { }

 getBooksList() {
    let names = this.apifetcherService.getBooksListNames();
    console.log(names);
  }
}

But I don’t know how to put this in my HTML file. I should save it to a variable:

booksIdNames: BookIdName[] | undefined;

But if I try this:

 getBooksList() {
    this.booksIdNames = this.apifetcherService.getBooksListNames();
  }

It gets the following error:

Type 'Promise<{ name: string; id: string; }[]>' is missing the following properties from type 'BookIdName[]': length, pop, push, concat, and 26 more.

In the end I would like to use this booksIdNames in this HTML:

<h2>Books</h2>
<ul>
  <li *ngFor="let book of booksIdNames">
    <span class="badge">Name: {{book.name}}; Id: {{book.id}}</span>
  </li>
</ul>

Source: Angular Questions

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.