2

I have a problem with Observable type, any idea?

import { PostModel } from '../model/postModel';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import * as _ from 'lodash';

class DataStore {

    private posts: PostModel[]  = [];

    private postListSubject = new Subject();

    public postsList$: Observable<PostModel[]> = this.postListSubject.asObservable();

    initializeLessonsList(newPost: PostModel[]) {
        this.posts = _.cloneDeep(newPost);
        this.broadcast();
    }

    addLesson(newPost: PostModel) {
        this.posts.push(_.cloneDeep(newPost));
        this.broadcast();
    }

    broadcast() {
        this.postListSubject.next(_.cloneDeep(this.posts));
    }
}

export const store = new DataStore();

on the line public postsList$: Observable<PostModel[]> = this.postListSubject.asObservable(); I am getting this error

[ts] Type 'Observable<{}>' is not assignable to type 'Observable'. Type '{}' is not assignable to type 'PostModel[]'. Property 'includes' is missing in type '{}'.

2 Answers 2

3

Add type information to your postListSubject declaration to allow the TypeScript compiler to infer the correct type of the Observable that is returned by Subject.asObservable():

private postListSubject = new Subject<PostModel[]>();
Sign up to request clarification or add additional context in comments.

Comments

0

this

const s = new Subject();
const o: Observable<Model[]> = s.asObservable();

results in the error you have.

Change it to this

const s = new Subject<Model[]>();
const o: Observable<Model[]> = s.asObservable();

and all is fine!

so...

in your code, change this:

private postListSubject = new Subject();

to this:

private postListSubject = new Subject<PostModel[]>();

If you don't provide a type, the type will default to {}! This is like an object with no properties, and indeed cannot be mapped to the PostModel[] type that you use.

have a nice day!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.