2016-08-05 65 views
0

我想从我的API获取评论。 那么,函数应该答应一个return? 有什么更好?克拉克还是承诺回报?Angular2:Promise return

而且我还有一个问题,promise返回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} 
]; 

和我在控制台这些:

valoare

数组[对象]

不确定

+0

如果回复承诺或明确的价值会更好吗?只有在需要进行异步调用(不能返回普通值)时才使用承诺,否则同步执行总是首选,除非您明确希望由于某种原因执行异步调用。 –

+0

我在Angular网站上看到这个例子..我刚才问,你知道为什么不工作?我喜欢在角度网站上。 –

+0

在Angular网站上,他们模拟异步调用,以便演示如何应对异步执行。这并不意味着它是首选。 –

回答

1

您需要与subscribe(...)

移动代码里面 then(...)(同为观测
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); 
     }); 
} 

Promisethen(...)的作用是启用链接调用,以便在前一个调用完成时执行后续调用。

异步执行意味着该调用已入队到事件队列中,并且同步代码(您的console.log())将在下一次执行。传递到.then(...)的代码最终在Promise解析时(通常是来自服务器的响应到达时)执行。