1

I am trying to access data from an WP Rest API that I have created that returns sample data.

I am trying to then access the array of data either via an iterator or just by something like data[0].

I'm very new to Angular, and particularly to Angular 5.

I have a model:

export class Tool {
  id: string;
  acf: object;

  constructor(id: string, acf: object) {
    this.id = id;
    this.acf = acf;
  }
}

A service that hits the API:

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { Observable } from 'rxjs/Observable';

    import { Tool } from 'app/models/tool';
    import { environment } from 'environments/environment';

    @Injectable()
    export class ToolsService {
      constructor(private http: HttpClient) {}

      getAll(): Observable<Tool[]> {
        return this.http.get(<myUrl>)
      }
    }

And then a component:

    import { Component, OnInit } from '@angular/core';
    import { Observable } from 'rxjs/Observable';

    import { Tool } from 'app/models/tool';
    import { ToolsService } from 'app/services/tools.service';

    @Component({
      selector: 'app-tools-documentation',
      templateUrl: './tools-documentation.component.html',
      styleUrls: ['./tools-documentation.component.scss'],
      providers: [ToolsService]
    })
    export class ToolsDocumentationComponent implements OnInit {
      tools$: Observable<Tool[]>;

      constructor(private toolsService: ToolsService) {}

      ngOnInit() {
        this.tools$ = this.toolsService.getAll()
      }
    }

I'm able to display the $tools on the page via something like: <pre>{{tools$ | async | json}}</pre>

But if I try to iterate over it (or access individual elements), I get errors around the types not matching or the Observable not actually being an array. How do I properly format this to access this data and iterate over it in the view? Every answer I find seems to use the old Angular 4 way of doing things and doesn't use HTTPClient.

0

1 Answer 1

3

The problem does not lie in whether you use Http or HttpClient.

To unwrap observables and loop through it:<div *ngFor="let tool of tools$ | async"> {{tool.id}}</div>

Sign up to request clarification or add additional context in comments.

2 Comments

And further it should be possible to do something like this: <ng-container *ngIf="tools$ | async as tools"> <div *ngFor="let tool of tools"> {{tool.id}}</div> <span>{{tools.length}}</span> </ng-container>
Thanks, I was using the AsyncPipe incorrectly and your two answers combined gave me exactly what I needed.

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.