[英]Angular 5 - HTTPClient + Observable + Displaying Data
I am trying to access data from an WP Rest API that I have created that returns sample data . 我正在尝试从我创建的返回示例数据的WP Rest API访问数据 。
I am trying to then access the array of data either via an iterator or just by something like data[0]
. 我试图通过迭代器或像
data[0]
类的东西访问数据数组。
I'm very new to Angular, and particularly to Angular 5. 我是Angular的新手,尤其是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: 遇到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>
我可以通过以下内容在页面上显示$ tools:
<pre>{{tools$ | async | json}}</pre>
<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. 但是如果我尝试迭代它(或访问单个元素),我会遇到不匹配的类型或Observable实际上不是数组的错误。 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.
我找到的每个答案似乎都使用旧的Angular 4做事方式而不使用HTTPClient。
The problem does not lie in whether you use Http
or HttpClient
. 问题不在于你是否使用
Http
或HttpClient
。
To unwrap observables and loop through it: <div *ngFor="let tool of tools$ | async"> {{tool.id}}</div>
要展开observable并循环遍历它:
<div *ngFor="let tool of tools$ | async"> {{tool.id}}</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.