Search code examples
angularangular-materialobservablesubscriptionsubscribe

I keep getting error of "Property subscribe does not exist on type void "


here is my ts file function which throws the error

post-list.componenet.ts



ngOnInit() {
  this.posts = this.postsService.getPosts();
  this.postsSub = this.postsService.getPostUpdateListener()
    .subscribe((posts: Post[]) => {
      this.posts = posts});
}


}



here is a service file

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

  getPosts() {
    return [...this.posts];
  }

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

  addPosts(title: string, content: string) {
    const post: Post = {title:  title, content: content};
    this.posts.push(post);
    this.postsUpdated.next([...this.posts]);
  }
}

I have imported the 'rxjs' dependency module and I can't seem to identify how to correct the error. The code runs on the browser but I don't get the desired output


Solution

  • Don't forget to return your data on your getPostUpdateListener()

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