-1

Service code

private posts: Post[] = [];
  private postsupdated = new Subject<Post[]>();
  getPost() {
    return [...this.posts]
  }
  getPostsUpdatedListener() {
    return this.postsupdated.asObservable()
  }

  addPosts(title: String, content: String) {
    const post: Post = { title: title, content: content }
    this.posts.push(post)
    this.postsupdated.next([...this.posts])
  }
  constructor() { }

component code

  Posts: Post[] = [];
  private postsSub = Subscription;
  ngOnInit(): void {
    this.Posts = this.postService.getPost();
    this.postsSub = this.postService.getPostsUpdatedListener()
      .subscribe((posts: Post[]) => {
        this.Posts = posts
      })
  }
  ngOnDestroy() {
    this.postsSub.unsubscribe();
  }

Type 'Subscription' is missing the following properties from type 'typeof Subscription': prototype, EMPTY and Property 'unsubscribe' does not exist on type 'typeof Subscription'.how to resolve it???

1 Answers1

1

You are assigning postsSub instead of declaring a type

private postsSub: Subscription;

Rewritten some code:

//Service
private _posts$ = new BehaviourSubject<Post[]>([]);
posts$ = this.posts.asObservable();

  addPosts(title: String, content: String) {
    const post: Post = { title: title, content: content };
    this._posts$.next([...this._posts$.getValue(), post])
  }


 // component
 posts$ = this.postService.posts$;
 _destroy$ = new Subject();

  ngOnInit(): void {
  // just for example, recommend using an async pipe in the template
    this.posts$.pipe(takeUntil(this._destroy$))
      .subscribe((posts: Post[]) => {
        // do whatever
      })
  }

 ngOnDestroy() {
    this._destroy$.next();
  }
Alexander
  • 3,019
  • 1
  • 20
  • 24