简体   繁体   English

从服务到组件的 Angular REST 数据

[英]Angular REST Data from service to component

I need help figuring out why my data isn't populating in the HTML.我需要帮助弄清楚为什么我的数据没有填充在 HTML 中。 I'm sure it's something dumb but I can't figure it out.我确定这是愚蠢的,但我无法弄清楚。 And I apologize if I left anything out and will gladly include it.如果我遗漏了任何内容,我很抱歉,并很乐意将其包含在内。

Below is the console results:下面是控制台结果:

undefined
core.js:13606 Angular is running in the development mode. Call enableProdMode() to enable the production mode.

below is the JSON i'm GETting through postman:下面是我通过邮递员获取的 JSON:

GET: http://localhost:3000/api/posts/获取: 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."
}

posts.service.ts 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));
  }

}

latests-posts.component.ts最新的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)
  };


}

latest-posts.component.html最新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>

In your API results there is no property with name "posts", though you have applied pipe to map res.posts, which will give you undefined.在您的 API 结果中,没有名称为“posts”的属性,尽管您已将管道应用于映射 res.posts,这将使您未定义。

Instead, you should return only json from service.相反,您应该只从服务中返回json

Example: posts.service.ts示例:posts.service.ts

public getAllPosts(): Observable<any> {
    let URI = `${this.serverApi}/api/posts/`;
    return this.http.get(URI)
      .pipe(map(res => res.json()));
  }

If you want to type cast your data at component, you can define its type at the time of subscribing it.如果你想在组件中类型转换你的数据,你可以在订阅它的时候定义它的类型。 like below.像下面。

component.ts组件.ts

public loadPosts() {
    this.postServ.getAllPosts().subscribe((response: Post[]) => {
       if(Array.isArray(response))
          this.posts = response
       else {
          this.posts = [];
          this.posts.push(response);
       }
    })
 }

The API call is an async function and need time to resolve. API 调用是一个异步函数,需要时间来解决。 It's missing an ngif in the HTML, so the DOM is updated, when the data arrives.它在 HTML 中缺少ngif ,因此当数据到达时更新 DOM。

Something like就像是

<div *ngIf="posts.length > 0"> Content to render when condition is true.</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM