错误TypeError:无法在SafeSubscriber._next读取未定义的属性“切片”

时间:2019-05-19 05:01:38

标签: node.js angular

当我尝试使用地图运算符ERROR TypeError:无法读取SafeSubscriber._next上未定义的属性“切片”。控制台会显示_next。我该如何解决此错误?

enter image description here

我将bellow .ts文件用作组件之一的服务文件

import { Post } from './post.model';
import {Injectable} from '@angular/core';
import {Subject} from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable({providedIn:'root'})

export class PostService{
private posts: Post[] = [];
private postUpdated = 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(transformedPost => {
    this.posts = transformedPost.posts;
    this.postUpdated.next([...this.posts]);
  });
}

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

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


}

}

这是我用作Post的模型

export interface Post {
  id:string;
  title: string;
  content: string;
}

1 个答案:

答案 0 :(得分:0)

您为ShipmentModel(s)传递了错误的参数:

http.post

如果要传递标题,则必须新建以创建post(url: string, body: any, options?: RequestOptionsArgs) : Observable<Response> Headers的新实例:

RequestOptions

甚至简化代码:

let headers = new Headers({ id: null, title: title, content: content  });
        let options = new RequestOptions({ headers: headers });

然后使用它:

let headers = new Headers({ id, title, content});
        let options = new RequestOptions({ headers: headers });

另外,请检查official docs中有关HTTP请求的标头。