我有一个组件从资产文件夹中加载本地json文件(仅包含名称)。由于HttpClient负责将数据格式化为json,因此此处未使用map。
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators'
export type cont= {name: string};
@Component({
selector: 'my-app',
template: `
1st List
<ul>
<li *ngFor="let contact of contacts | async">{{contact.name}}</li>
</ul>
2st List
<ul>
<li *ngFor="let contact of contacts2 | async">{{contact.name}}</li>
</ul>
`
})
export class AppComponent {;
contacts: Observable<cont[]>;
contacts2: Observable<cont[]>;
constructor (http: HttpClient) {
this.contacts = http.get<cont[]>('http://localhost:4200/assets/contacts.json');
setTimeout(() => this.contacts2 = this.contacts, 500);
}
}
Contacts.json
{
"items": [
{ "name": "Mark Twain" },
{ "name": "Sherlock Holmes" }
]
}
可以通过http://localhost:4200/assets/contacts.json在浏览器上获取数据,但是当我尝试通过异步管道渲染数据时,出现以下错误。尝试了多种方法将可观察的转换为可观察的[[]>,但是没有一种方法可以通过。 这是怎么了。
(如何将httpclient上的json数据转换为Array?( 试图跟随类似的帖子,但没有帮助 )? >答案 0 :(得分:4)
您要遍历一个对象:
{
"items": [
{ "name": "Mark Twain" },
{ "name": "Sherlock Holmes" }
]
}
您应该遍历contacts.items
<ul>
<li *ngFor="let contact of (contacts | async)?.items">{{contact.name}}</li>
</ul>
或仅使用可观察的地图:
const url = 'http://localhost:4200/assets/contacts.json';
this.contacts = http.get<cont[]>(url).pipe(map(data => data.items));
使用Symbol.iterator
我之所以添加它,只是因为它很有趣(我认为),尽管在这种情况下不切实际。
我可以在异步对象上保留迭代:
<ul>
<li *ngFor="let contact of contacts | async">{{contact.name}}</li>
</ul>
但是我将通过添加iterable protocol将这个对象转换为可迭代的:
const url = 'http://localhost:4200/assets/contacts.json';
this.contacts = http.get<cont[]>(url).pipe(
map((data: any) => {
data[Symbol.iterator] = () => data.items[Symbol.iterator]();
return data;
})
);
行
data[Symbol.iterator] = () => data.items[Symbol.iterator]()
将对象上的迭代(默认情况下是不可能)重定向到其items
数组上的迭代。
我创建了一个STACKBLITZ来演示
答案 1 :(得分:0)
这肯定会正确地定义正确的变量
当变量中的数据json不是数组格式时会发生这种情况。像这样定义变量
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <sys/socket.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <netdb.h>
#include <stdlib.h>
int main() {
struct ifaddrs *ifa;
if (getifaddrs(&ifa) == -1) {
perror("getifaddrs failed");
exit(1);
}
for (struct ifaddrs *i = ifa; i; i = i->ifa_next) {
printf("Name %s has ", i->ifa_name);
if (i->ifa_addr == NULL) {
printf("no address!");
} else if (i->ifa_addr->sa_family == AF_INET) {
printf("ipv4 (ie. ethernet, ie. IEEE 802.3)");
} else if (i->ifa_addr->sa_family == AF_INET6) {
printf("ipv6");
} else if (i->ifa_addr->sa_family == AF_BLUETOOTH) {
printf("bluetooth");
} else {
printf("unhandled!");
}
printf("\n");
}
}