George Valentin George Valentin - 4 months ago 47
Javascript Question

Angular2: Promise return

I want to get the comments from my API.
So, the function should promise a return?
What is better? Clasic or promise return?

And I have still a problem, the promise return return undefined.

comments.component.ts

import { Component, OnInit } from '@angular/core';
import { CommentService } from '../services/comment.service';
import { Comment } from '../class/Comment';

@Component({
template: 'dadada',
providers: [CommentService]
})

export class CommentsComponent implements OnInit {
coms: Comment[];

constructor(private commentService: CommentService) {
}

ngOnInit() {
console.log( this.commentService.testfunction() );

this.commentService.get_all_comments().then((data) => {
this.coms = data;
});
console.log ( this.commentService.get_all_comments2() );
console.log ( this.coms );
}
}


comment.service.ts

import { Injectable } from '@angular/core';
import { Comment, Comments } from '../class/Comment';

@Injectable()
export class CommentService {
testfunction() {
return 'valoare';
}
get_all_comments() {
return Promise.resolve(Comments);
}
get_all_comments2() {
return Comments;
}
}


Comment.ts

export class Comment {
id: number;
text: string;
author: string;
created_at: number;
updated_at: number;
}

export const Comments: Comment[] = [
{id: 1, text: 'Look I am a test comment.', author: 'Chris Sevilleja', created_at: 0, updated_at: 0}
];


And I get in console these:


valoare

Array [ Object ]

undefined

Answer

You need to move the code inside the then(...) (same for observables with subscribe(...)

ngOnInit() { 
    console.log( this.commentService.testfunction() ); 

    this.commentService.get_all_comments().then((data) => {
        this.coms = data;
        console.log ( this.commentService.get_all_comments2() );
        console.log ( this.coms );
      });
}

The purpose of Promise and then(...) is to enable to chain calls so that a subsequent call is executed when the previous one completes.

Async execution means that the call is enqueued into the event queue and sync code (your console.log()) is executed next. The code passed to .then(...) is eventually executed when the Promise resolves (usually when the response from the server arrives).