angular - 从服务到组件的 Angular REST 数据
问题描述
我需要帮助弄清楚为什么我的数据没有填充到 HTML 中。我确定这很愚蠢,但我无法弄清楚。如果我遗漏了任何内容,我深表歉意,并很乐意将其包括在内。
下面是控制台结果:
undefined
core.js:13606 Angular is running in the development mode. Call enableProdMode() to enable the production mode.
下面是我通过邮递员获取的 JSON:
获取:http://localhost:3000/api/posts/
{
"postName": "Fun in the Sun",
"postDate": "10/23/1993",
"caption": "Hear all about my trip to lalaland",
"mainImage": "https://placeholder.net/20x20",
"suppementalImage1": "https:// placeholder.net/20x20",
"suppementalImage2": "https:// placeholder.net/20x20",
"suppementalImage3": "https:// placeholder.net/20x20",
"suppementalImage4": "https:// placeholder.net/20x20",
"suppementalImage5": "https:// placeholder.net/20x20",
"suppementalImage6": "https:// placeholder.net/20x20",
"content": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptates deleniti quas dolorem quis nulla debitis praesentium dolores eveniet aliquam! At expedita vel consequatur, sit laboriosam ducimus molestiae recusandae ipsam sunt.Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptates deleniti quas dolorem quis nulla debitis praesentium dolores eveniet aliquam! At expedita vel consequatur, sit laboriosam ducimus molestiae recusandae ipsam sunt.Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptates deleniti quas dolorem quis nulla debitis praesentium dolores eveniet aliquam! At expedita vel consequatur, sit laboriosam ducimus molestiae recusandae ipsam sunt."
}
post.service.ts
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent, SubscriptionLike, PartialObserver } from 'rxjs';
import { Post } from '../models/post'
import { map } from 'rxjs/operators'
@Injectable({
providedIn: 'root'
})
export class PostsService {
constructor(private http: Http) { }
private serverApi = 'http://localhost:3000';
public getAllPosts(): Observable<Post[]> {
let URI = `${this.serverApi}/api/posts/`;
return this.http.get(URI)
.pipe(map(res => res.json()))
.pipe(map(res => <Post[]>res.posts));
}
}
最新的posts.component.ts
import { Component, OnInit } from '@angular/core';
import { PostsService } from '../services/posts.service';
import { Post } from '../models/post';
@Component({
selector: 'app-latest-posts',
templateUrl: './latest-posts.component.html',
styleUrls: ['./latest-posts.component.css']
})
export class LatestPostsComponent implements OnInit {
private posts: Post[] = []; //creats a private variable of posts with type of model List an creates an empty array
constructor(private postServ: PostsService) { };
ngOnInit() {
this.loadPosts()
console.log(this.loadPosts()); //loads all lists on init
};
public loadPosts() {
this.postServ.getAllPosts().subscribe(response => this.posts = response)
};
}
最新的posts.component.html
<table id="table">
<thead>
<tr>
<th>Priority Level</th>
<th>Title</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let post of posts">
<td>{{post.name}}</td>
<td>{{post.date}}</td>
<td>{{posts.caption}}</td>
</tr>
</tbody>
</table>
解决方案
在您的 API 结果中,没有名称为“posts”的属性,尽管您已将管道应用于映射 res.posts,这将使您未定义。
相反,您应该只json
从服务中返回。
示例:posts.service.ts
public getAllPosts(): Observable<any> {
let URI = `${this.serverApi}/api/posts/`;
return this.http.get(URI)
.pipe(map(res => res.json()));
}
如果你想在组件中类型转换你的数据,你可以在订阅它的时候定义它的类型。如下所示。
组件.ts
public loadPosts() {
this.postServ.getAllPosts().subscribe((response: Post[]) => {
if(Array.isArray(response))
this.posts = response
else {
this.posts = [];
this.posts.push(response);
}
})
}
推荐阅读
- python - 将手动构建的opencv与其他版本的python一起使用
- r - 以宽格式转换数据,同时保持变量的对齐
- node.js - 在 Angular @ngx-translate 上翻译 .ts 文件
- reactjs - ReactJS 构建错误 - 无法读取属性
- seo - 如何在shopify中替换url产品
- angular - 角度错误 TS2564 属性“formGroup”没有初始化程序
- python - 黑色格式化程序 - 如何仅扫描选定的目录
- javascript - 用于库文件的 Webpack/Typescript,如何进行 treeshake 导入,而不是 treeshake 导出?
- firebase - Firebase 计划处理超过 1000 条记录会导致超时
- c - 读取文本文件并搜索文本