fbredius/storybook

View on GitHub
docs/snippets/angular/document-screen-fetch.ts.mdx

Summary

Maintainability
Test Coverage
```ts
// YourPage.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'document-screen',
  template: `
    <div>
      <div *ngIf="error"><p>There was an error fetching the data!</p></div>
      <div *ngIf="loading"><p>Loading...</p></div>
      <div *ngIf="!loading && subdocuments.length > 0">
        <page-layout [user]="user">
          <document-header [document]="document"></document-header>
          <document-list [documents]="subdocuments"></document-list>
        </page-layout>
      </div>
    </div>
  `,
})
export class DocumentScreen implements OnInit {
  user: any = { id: 0, name: 'Some User' };

  document: any = { id: 0, title: 'Some Title' };

  subdocuments: any = [];

  error = false;
  loading = true;

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http.get<any>('https://your-restful-endpoint').subscribe({
      next: (data) => {
        this.loading = false;
        this.user = data.user;
        this.document = data.document;
        this.documents.data.subdocuments;
      },
      error: (error) => {
        this.error = true;
      },
    });
  }
}
```