试图从数据库中获取数据。角度6

时间:2018-07-15 09:19:00

标签: angular typescript

嗨,我正在尝试从数据库中获取数据到表。我创建了这样的服务

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Subject } from "rxjs";
import { map } from 'rxjs/operators';

import { Post } from "./post.model";

@Injectable({ providedIn: "root" })
export class PostsService {
  private posts: Post[] = [];
  private postsUpdated = new Subject<Post[]>();

  constructor(private http: HttpClient) {}

  getPosts() {
    this.http
      .get<{ message: string; posts: any }>(
        "http://localhost:3000/api/posts"
      )
      .pipe(map((postData) => {
        return postData.posts.map(post => {
          return {
            title: post.title,
            content: post.content,
            id: post._id
          };
        });
      }))
      .subscribe(transformedPosts => {
        this.posts = transformedPosts;
        this.postsUpdated.next([...this.posts]);
      });
  }

  getPostUpdateListener() {
    return this.postsUpdated.asObservable();
  }

  addPost(title: string, content: string) {
    const post: Post = { id: null, title: title, content: content };
    this.http
      .post<{ message: string, postId: string }>("http://localhost:3000/api/posts", post)
      .subscribe(responseData => {
        const id = responseData.postId;
        post.id = id;
        this.posts.push(post);
        this.postsUpdated.next([...this.posts]);
      });
  }

  deletePost(postId: string) {
    this.http.delete("http://localhost:3000/api/posts/" + postId)
      .subscribe(() => {
        const updatedPosts = this.posts.filter(post => post.id !== postId);
        this.posts = updatedPosts;
        this.postsUpdated.next([...this.posts]);
      });
  }
}

运行代码时,我遇到两个不同的错误:

如果我使用 mozilla ,我会得到:

  

错误TypeError:“ _ this.posts未定义”

如果我使用 chrome ,我会得到:

  

core.js:1542错误TypeError:无法读取以下内容的属性“切片”   未定义       在SafeSubscriber._next(posts.service.ts:39)

任何人都知道为什么会这样吗?谢谢

1 个答案:

答案 0 :(得分:0)

请确保this.posts调用中this.updatedPosts.next([...this.posts])不为空。您可以用this.updatedPosts.next(this.posts)代替,因此在帖子为空的情况下,您不会遇到任何运行时错误