1

I am trying to initialize an array from an observable. However I get an compilation error saying:

enter image description here

Component:

export class LeaderBoardComponent implements OnInit {
    leaderBoardTableData: Array<LeaderBoardModel>;
    constructor(private appStore: Store<AppStore>,

        private leaderBoardService: LeaderBoardService) {
        this.leaderBoardService.getLeaderBoard()
            .skipWhile((data) => { return _.isEmpty(data) })
            .subscribe((data) => {
                if (!_.isEmpty(data)) {
                    this.leaderBoardTableData = this.leaderBoardService.getLeaderBoard();
                }
            });
    }

Service:

 getLeaderBoard(): Observable<LeaderBoardModel> {
        return this.httpUtil.get(this.appConstants.END_POINT_LEADERBOARD)
            .map(response => <LeaderBoardModel>response.json());
    }

2 Answers 2

3

getLeaderBoard() method returns an observable of a single LeaderBoardModel element. So upon subscription you have to push the subscribed value (which is data) to your leaderBoardTableData in the component.

I think it should be:

.subscribe((data) => {
    if (!_.isEmpty(data)) {
        this.leaderBoardTableData = [data];
        // or `this.leaderBoardTableData.push(data);` , you have to make sure that `leaderBoardTableData` is already instantiated though
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

You must subscribe the this.leaderBoardService.getLeaderBoard() because you cannot assign an Observable to an array.

So do this in your code:

this.leaderBoardService.getLeaderBoard().subscribe(data => {
    this.leaderBoardTableData = data;
});

If you wanted leaderBoardTableData to be equal to an observable so that your code did not have to change, you could just change the type definition from:

leaderBoardTableData: Array<LeaderBoardModel>;

To:

leaderBoardTableData: Observable<LeaderBoardModel>;

Also be cognizant of the fact that you have a generic Array type, which means the return value of your observable must also be a generic Array type or you will get a similar type checking error from the compiler.

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.